It is best not to iterate through the array in JavaScript

Source: Internet
Author: User

Look at a piece of code first

1 <! DOCTYPE html> 2 }16         //use for in to traverse the array for         (var. k in arr) {             console.log (k, "type:" +typeof k,arr[k]);         }20     </script>21 </body>22 

This code shows a bit of the difference between A for loop traversal array and a for-in loop through an array:

  The standard for-loop i is the number type, which represents the subscript of the array, but I in the Foreach loop represents the array's key is the string type.

It's not a pit, it's just a little different.

Look at the code again.

1 <! DOCTYPE html> 2 

This code is on the top of the code, based on the array to do a bit of expansion. Very simple, just add a function. But let's see what happens with the run:

The result of the output, there is a row, this line is our extension of a function, not our definition in the array of values. That's the problem.

In summary, with for...in ... In general, it does work correctly.

But if we are using foreach to iterate through an array in the project, let's say that one day he's not careful to extend the JS native array class, or introduce an external JS framework that extends the native array. That's the problem.

So it's best to iterate through the array with a For loop

It is best not to iterate through the array in JavaScript

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.