This works:
for (var i = 0; i < this.size(); i++) {
values.push(this.cards[i].value);
}
but this doesn't:
for (var card in this.cards) {
values.push(card.value);
}
Why?
This works:
for (var i = 0; i < this.size(); i++) {
values.push(this.cards[i].value);
}
but this doesn't:
for (var card in this.cards) {
values.push(card.value);
}
Why?
Because in for...in
loops, the variable is the key, not the value.
It should be:
for (var card in this.cards) {
values.push(this.cards[card].value);
}
for (var card in this.cards) {
values.push(card.value);
}
... card
will be the index number, not the value.
The for..in
loop enumerates over the property names of an object, not the property values. Should be:
for ( var key in this.cards ) {
values.push( cards[key].value );
}
One downside of for..in
is that it also enumerates over inherited property names (of course, only if the corresponding property is enumerable).
Also, consider this:
var values = this.cards.map(function ( card ) {
return card.value;
});
Because the for (var x in y)
syntax loops over PROPERTIES of the object (keys), which can be members of the array if it's an array, but also other enumerable properties.
For example:
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
Will print out all the properties (JohnDoe25), but an array has members that are elements (e.g. the values contained in the array) as well as prototypical properties. Consider this:
// Somewhere deep in your javascript library...
Array.prototype.foo = 1;
// Now you have no idea what the below code will do.
var x, a = [1,2,3,4,5];
for (x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'
}
x
will come up as foo
's value at some point in the loop, but that's almost never what would be intended.
I would say don't use for(var x in y)
unless you understand what it does -- not trying to be a prick, just save you from a lot of hair-pulling and head-scratching, which I myself went through at one point :/