There are two ways we iterate through the array in JS.
Code:
var array=[' a ']
Standard for Loop
for (Var i=1;i<array.length;i++) {
Alert (Array[i])
}
foreach Loop
for (var i in array) {
Alert (Array[i])
}
In normal cases, the above two ways of traversing an array result in the same way. First of all, the first difference between the two
The standard for loop i is the number type, which represents the subscript of the array, but I in the Foreach loop represents the array key is the string type because everything in JS is an object. Try the alert yourself (typeof i); this difference is a minor problem. Now I add the following code, the above results are different.
Code
Expanded JS native array
Array.prototype.test=function ()
}
We found that the standard for loop is still a true array loop, but at this point the Foreach loop prints out the test method I just wrote. This is the maximum difference between a for and a foreach traversal array, and if we are using foreach to iterate through an array in the project, let's say that one day you are not careful to extend the JS native array class, or introduce an external JS framework that extends the native array.
Suggestions
1. Do not iterate through the array with for in, all uniformly using the standard for loop variable array (we cannot guarantee that the JS we introduce will use the prototype extension native array)
2. If you want to extend the native class of JS, do not use prototype.
The difference between a Java script array traversal for and for