It is best not to use for...in to iterate through the array in JavaScript

Source: Internet
Author: User

Look at a piece of code first

var arr = [2,3,4,5];    for (var i = 0; i < arr.length; i++) {        Console.log (i, "type:" +typeof i,arr[i]);    }   for (Var j in arr) {       Console.log (J, "type:" +typeof j,arr[j]);   }

Results

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.
However: if we expand the array on the basis of the above code, just add the function and see what the following results are
    var arr = [2,3,4,5];    Array.prototype.remove = function (val) {console.log ("the deletion method added in the array!");}    ;    for (var i = 0; i < arr.length; i++) {        Console.log (i, "type:" +typeof i,arr[i]);    }   for (Var j in arr) {       Console.log (J, "type:" +typeof j,arr[j]);   }

The results are as follows:

The result of the output of the for...in is more than one line, the extra line is our extended function, not the value we define in the array

So when we're traversing the array, it's best not to use for...in

It is best not to use for...in 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.