The two functions are used to traverse the object, but why is there a for-in statement that also has a for every in statement, and then looked at the next for every in development document, for every in is published as part of the E4X standard in JavaScript 1.6, And it's not part of the ECMAScript standard.
Difference One:
For in is published in JavaScript 1.0.
For all in is published as part of the E4X standard in JavaScript 1.6, and it is not part of the ECMAScript standard.
This will mean that there are compatibility issues with various browsers. For every in, not supported for many browsers. For example, browsers such as IE6,IE7,IE8 are not supported.
Difference Two:
var array=[' a ']
Standard for Loop
for (var i=1;i<array.length;i++) {
alert (array[i])}//foreach loop for (var i in array) {alert ( array[i])}
in normal cases, the above two ways of traversing an array result in the same way. 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 key is the string type because everything in JS is an object. Try the alert yourself (typeof i); this difference is a minor problem. Now I add the following code, the above results are different.
array.prototype.test=function()}
Try what the above code does. We found that the standard for loop is still a true array loop, but at this point the Foreach loop prints out the test method I just wrote. This is the maximum difference between a for and a foreach traversal array, and if we are using foreach to iterate through an array in the project, let's say that one day you are not careful to extend the JS native array class, or introduce an external JS framework that extends the native array. That's the problem. Two points for this recommendation
- Do not iterate through the array with for in, all uniformly using the standard for loop variable array (we cannot guarantee that the JS we introduce will use the prototype extension native array)
- If you want to extend the native class of JS, do not use prototype.
Traversing a normal array, it is recommended to use the native traversal method for, not for convenience, because there are browser compatibility issues with both for and for, and there is no guarantee that they will traverse the sequence of arrays (if not required in order, you can use for in, but I do not recommend).
- Traversing an object, because the for does not provide an ideal traversal, you can only select other methods. It is recommended here to use the for-in, the difference from the above, for-in is more advantageous for the for-in can get the index and attribute values, and for each can only get the property value, and for each is not supported in many low-version browsers.
The difference between for/in and for in JavaScript