Differences between javascript Array traversal for and forin _ javascript skills

Source: Internet
Author: User
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.

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.