Behavior difference between for and for..in

6

I have the following code that works exactly as expected (that 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 is not this? Why do you always do that last loop and print your own function? Is there any implicit property that does not go into the count ( this.length )? If yes, then there is 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();
    
asked by anonymous 15.12.2016 / 11:55

3 answers

6

The problem here is that for...in is a method for Objects, and will fetch enumerable properties from it, ie : the ones themselves and those defined in prototype . Since you are using a method of objects in an array, the function is also passed as a property of the object. However is not a property of the instance but rather of your prototype , then it is possible to filter these "none" properties with .hasOwnProperty .

Repair here:

var runners = ['Miguel', 'Celeste'];
Array.prototype.winner = function() {
    for(var i in this) {
		console.log(i, this.hasOwnProperty(i));
    }
}

runners.winner();

However, for ... in is not an arrays method, but there is a recent one that is. Using for ... of everything is right, starting from the principle that the browser is modern:

var runners = ['Miguel', 'Celeste'];
Array.prototype.winner = function() {
  for (var nome of this) {
    console.log(nome);
  }
}
runners.winner();
    
15.12.2016 / 22:42
4

The first one for traditional , sweeping the array . It accesses only the elements of the object of type Array , but not their properties. It is similar to the new for...of %.

Since for...in sweeps all the properties of the object, not just its elements.

has a question with more detailed information about for % .

Note that both are sweeping the this referred to own object. But what object are we talking about in this loose code? It is the global script DOM. Then all the script symbols are contained in this implicitly created global object. This is why the function is part of this object.

Question explaining this .

    
15.12.2016 / 12:27
3

The third index of your array is the winner itself, that is, there is the index 0, the 1 and the winner (which is an index tbm). And as it was said by @bigown, for in sweeps, in addition to the indexes with the content that you created, the prototypes of the object.

    
15.12.2016 / 22:07