The javascript array traverses the difference between for and for in

  • 2020-03-30 04:30:06
  • OfStack

There are two ways to iterate over groups in js


var array=['a']
//The standard for loop is
for(var i=1;i<array.length;i++){
    alert(array[i])
}
//Foreach loop
for(var i in array){
    alert(array[i])
}

Normally, the above two ways of traversing groups give the same result. First, the first difference between the two

The I in the standard for loop is of type number, which is the index of the array, but the I in the foreach loop is of type string, because everything in js is an object. Try alert(typeof I) for yourself; The difference is minor. Now I add the following code, the above execution result is different.


//Js native Array
is extended Array.prototype.test=function()
 
}

Try what the above code does. We found that the standard for loop is still a real loop against the array, but now the foreach loop is printing out the test method I just wrote. This is the big difference between for and foreach traversing groups. If we were to use foreach traversing groups in our project, suppose someone accidentally extended their native Array class in order to extend js or introduced an external js framework that also extended native Array. That's the problem.

There are two further Suggestions

1. Don't iterate over groups with "for in", and use the standard for loop variable Array (we cannot guarantee whether the js we introduce will use prototype to extend the native Array).
2. If you want to extend js native classes, don't use prototype


Related articles: