On the difference between for in and for each in in javascript

  • 2020-06-01 08:15:03
  • OfStack

The difference between 1:

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

The difference between 2:

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


  for (var i in  A rectangle ){
    alert( i + " . " +  A rectangle [i] );
  }

The results were, in order: high, 15; Wide, 25;


  for each (var i in  A rectangle ){
    alert( i + " . " +  A rectangle [i] );
  }

The results are, in order: 15, undefined; 25, undefined;

The value of the variable i of the two traversal methods is different. for each in cannot get the property name of the object, but only the property value.

Finally, the following Suggestions are summarized:

(1) common array traversal, recommend the use of native for traversal method, don't covet convenient, because for in and for each in browser compatibility problems, can not guarantee them to array traversal sequence (if the order does not make the request, you can use for in, but I don't recommend), who are interested in, you can read under 1 of article in the "about js for in defects".

(2) traversing the object. Since for cannot provide an ideal traversal, it has to choose other methods. It is recommended to use for in. According to the differences explained above, for in has more advantages than for each. for in can get indexes and property values, while for each can only get property values.

That's all for this article, I hope you enjoy it


Related articles: