8
I have the following code that works exactly as expected (which is to go through the array, showing ONLY each element, in this case "Miguel" and "Celeste"):
var runners = ['Miguel', 'Celeste'];
Array.prototype.winner = function() {
for (var i = 0; i < this.length; i++) {
console.log(runners[i]);
}
}
runners.winner();
My question is why not this one? Why does it always make that last loop and print the function itself? Is there any implicit property that does not enter for the count (this.length
)? If yes, then there’s no way to do this with for(var i in this) {
right?
var runners = ['Miguel', 'Celeste'];
Array.prototype.winner = function() {
for(var i in this) {
console.log(runners[i]);
}
}
runners.winner();
I feel bad about doing this, and I’m really sorry about the mustache, which I also explained well and had already accepted your answer. But you really clarify it better and even give a workaround to use
for(var x in...
in the same (although I now know that in this context it would not make sense). Obgado– Miguel
@Miguel yes, the
for..of
respects the list/array order, and is a short version for arrays likefor..in
is for Objects. Thefor..in
does not, however, guarantee that the properties of an object are iterated in the same order in different browsers. Butfor..of
respects the order.– Sergio
Got it, obgado Sergio
– Miguel