There are two ways to traverse arrays in js
var array=['a']
//Standard for loop
for(var i=1;i<;i++){
alert(array[i])
}
//foreach loop
for(var i in array){
alert(array[i])
}
Under normal circumstances, the above two ways of traversing the array are the same. First of all, let's talk about the first difference between the two
The i in the standard for loop is of number type, which represents the subscript of the array, but the i in the foreach loop represents the key of the array is of string type, because everything in js is an object. Try it yourself alert(typeof i); this difference is a small problem. Now I add the following code, and the execution results above will be different.
//Extended js native Array
=function()
}
Try to see what the above code executes. We found that the standard for loop is still real looping on arrays, but at this time the foreach loop is printed out of the test method I just wrote. This is the biggest difference between for and foreach traversing arrays. If we use foreach to traverse arrays in the project, suppose there is a day when someone accidentally expands the native Array class of js, or introduces an external js framework to extend native Array. Then the question arises.
Two more points to suggest
1. Do not use for in to traverse the array, and use standard for loop variable arrays in unison (we cannot guarantee whether the js we introduced will use prototype to extend native Array)
2. If you want to extend the native class of js, don’t use prototype