Home > Web Front-end > JS Tutorial > Detailed explanation of the difference between javascript array traversal for and for in_javascript skills

Detailed explanation of the difference between javascript array traversal for and for in_javascript skills

WBOY
Release: 2016-05-16 16:29:18
Original
1496 people have browsed it

There are two ways to traverse arrays in js

Copy code 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 results of the above two methods of traversing arrays are the same. First let’s talk about the first difference between the two

The i in the standard for loop is of type number, which represents the subscript of the array, but the i in the foreach loop represents that the key of the array is of type string, because everything in js is an object. Try it yourself alert(typeof i); This difference is a minor problem. Now that I add the following code, the above execution results will be different.

Copy code The code is as follows:

//Extended js native Array
Array.prototype.test=function()

}

Try it out and see what the above code does. We found that the standard for loop still truly loops over the array, but at this time the foreach loop prints out the test method I just wrote. This is the biggest difference between for and foreach to traverse the array. If we use foreach to traverse the array in the project, suppose one day someone accidentally extends the native Array class of js, or introduces an external js framework and also extends the native Array. . Then comes the problem.

Two more suggestions

1. Do not use for in to traverse the array, 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 classes of js, don’t use prototype

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template