JavaScript array traversal for and for in difference _javascript tips

Source: Internet
Author: User
Tags javascript array

There are two ways to iterate through an array in JS

Copy Code code as follows:

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])
}

Normally, the above two ways of traversing an array result in the same way. First, the first difference between the two.

The I in the standard for loop is the number type, which represents the subscript of the array, but the I in the Foreach loop indicates that the key of the array is a string type because everything in JS is an object. Try alert yourself (typeof i); this difference is a small problem. Now I add the following code, the results of the above implementation is different.

Copy Code code as follows:

The expansion of JS native array
Array.prototype.test=function ()

}

Try what the above code does. We found that the standard for loop has a real array loop, but at this point the Foreach loop prints out the test method I just wrote. This is the biggest difference between a for and a foreach traversal array, and if we're using a foreach traversal array in the project, suppose one day someone accidentally expands the native array for the purpose of extending the JS native array class, or introducing an external JS framework. That's the problem.

Then this suggestion two points

1. Do not use for-in traversal array, all unified using the standard for loop variable array (we cannot guarantee that the JS we introduced will adopt prototype extended native array)
2. If you want to extend the original class of JS, do not use prototype

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.