Differences between for in and for each in javascript: javascripteach

Source: Internet
Author: User

Differences between for in and for each in javascript: javascripteach

Difference 1:

For in is released in javascript 1.0.
For each in is released in javascript 1.6 as part of the E4X standard, and is not part of the ECMAScript standard.
This means there are compatibility issues with various browsers. For each in is not supported by many browsers. For example, Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 are not supported.

Difference 2:

For example, var rectangle = {Height: "15", width: "25 "};

For (var I in rectangle) {alert (I + "," + rectangle [I]);}

The results are as follows: height, 15; width, 25;

For each (var I in rectangle) {alert (I + "," + rectangle [I]);}

The results are as follows: 15, undefined; 25, undefined;

The values of variable I in the two traversal methods are different. for each in cannot obtain the attribute name of the object, and only the attribute value can be obtained.

Finally, we will summarize the usage suggestions:

(1) traverse common arrays. We recommend that you use the native Traversal method for. Do not greedy for the convenience of graphs, because for in and for each in both have browser compatibility problems, they cannot guarantee the traversal order of the array (if not required, you can use for in, but I do not recommend it, you can read the next article about defects of for in JavaScript.

(2) traverse objects. Because for cannot provide ideal traversal, you can only select other methods. We recommend that you use for in. From the difference described above, for in is more advantageous than for each. for in can obtain indexes and attribute values, while for each can only obtain attribute values, in addition, for each is not supported in many earlier browsers.

The above is all the content of this article. I hope you will like it.

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.