This article mainly introduces the differences between for and forin for javascript Array traversal. It is a very good article. We recommend it to our friends here. There are two methods to traverse arrays in js:
The Code is as follows:
Var array = ['a']
// Standard for Loop
For (var I = 1; I alert (array [I])
}
// Foreach Loop
For (var I in array ){
Alert (array [I])
}
Under normal circumstances, the above two methods traverse the array have the same result. First, the first difference between the two
In the standard for loop, I is of the number type, indicating the subscript of the array, but in the foreach loop, I indicates that the key of the array is of the string type, because everything in js is an object. Try alert (typeof I) by yourself. The difference is a small problem. Now I add the following code, and the above execution results are different.
The Code is as follows:
// Extends the native Array of js
Array. prototype. test = function ()
}
Try to see what the above code is executed. We found that the standard for loop is actually an array loop, but now the foreach loop writes and prints out the test method I just wrote. This is the biggest difference between for and foreach traversal arrays. If we use foreach to traverse arrays in the project, suppose one day someone accidentally wants to expand the native Array class of js, or introduce an external js framework to extend the native Array. That's the problem.
Two more points are recommended.
1. Do not use for in to traverse the Array. All 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 the native class of js, do not use prototype.