Home  >  Article  >  Web Front-end  >  A brief discussion on the difference between for in and for each in in javascript_javascript skills

A brief discussion on the difference between for in and for each in in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:02:34995browse

Difference 1:

for in is released in javascript 1.0.
For each in was released in JavaScript 1.6 as part of the E4X standard, while it is not part of the ECMAScript standard.
​ ​ ​ This will mean that there are compatibility issues with various browsers. for each in, which is not supported by many browsers. For example, it does not support IE6, IE7, IE8 and other browsers.

Difference 2:

Example: var rectangle = { height: "15", width: "25" };

  for (var i in 长方形){
    alert( i + "," + 长方形[i] );
  }

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

  for each (var i in 长方形){
    alert( i + "," + 长方形[i] );
  }

The results are: 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, but can only obtain the attribute value.

Finally, summarize the usage suggestions:

(1) To traverse an ordinary array, it is recommended to use the native traversal method for. Do not be greedy for convenience, because both for in and for each in have browser compatibility issues and cannot guarantee the order in which they traverse the array (if the sequence is If there is no requirement, you can use for in, but I don’t recommend it). If you are interested, you can read the next article "A brief analysis of the defects of for in in js".

(2) Traverse objects. Since for cannot provide ideal traversal, other methods can only be chosen. It is recommended to use for in here. From the differences explained above, for in has more advantages than for each. for in can obtain index and attribute values, while for each can only obtain attribute values. Moreover, for each is not available in many lower version browsers. Not supported.

The above is the entire content of this article, I hope you all like it

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn