This article by Bole Online-elviskang translation, into the forest School draft. without permission, no reprint!
English Source: adripofjavascript.com. Welcome to join the translation team.
The for...in loop of JavaScript is used to iterate over an enumerable (enumerable) property in an object:
1234567891011121314151617 |
var tMinus = {
two:
"Two"
,
one:
"One"
,
zero:
"Blast off!"
};
var countdown =
""
;
for (
var step
in tMinus) {
countdown += tMinus[step] +
"n"
;
}
console.log(countdown);
// => "Two
// One
// Blast Off!
// "
|
Because the for...in loop supports all JavaScript objects, it can also be used in array objects:
1234567891011121314151617 |
var tMinus = [
"Two"
,
"One"
,
"Blast off!"
];
var countdown =
""
;
for (
var step
in tMinus) {
countdown += tMinus[step] +
"n"
;
}
console.log(countdown);
// => "Two
// One
// Blast Off!
// "
|
However, there are three problems with traversing an array in such a way. First, the for...in loop iterates through all the enumerable properties in the prototype chain of the array object:
1234567891011121314151617181920 |
Array.prototype.voice =
"James Earl Jones"
;
var tMinus = [
"Two"
,
"One"
,
"Blast off!"
];
var countdown =
""
;
for (
var step
in tMinus) {
countdown += tMinus[step] +
"n"
;
}
console.log(countdown);
// => "Two
// One
// Blast Off!
// James Earl Jones
// "
|
However, we can use the hasOwnProperty function to avoid this problem:
123456789101112131415161718192021 |
Array.prototype.voice =
"James Earl Jones"
;
var tMinus = [
"Two"
,
"One"
,
"Blast off!"
];
var countdown =
""
;
for (
var step
in tMinus) {
if (tMinus.hasOwnProperty(step)) {
countdown += tMinus[step] +
"n"
;
}
}
console.log(countdown);
// => "Two
// One
// Blast Off!
// "
|
In addition, as mentioned in the ECMAScript5.1 specification, the for...in loop may traverse the properties of an object in any order .
The order in which attributes are accessed is irrelevant for unordered normal objects. But sometimes you may not want JavaScript engine to process your array elements in a random order, because it can cause unpredictable results:
12345 |
console.log(countdown); // => "Blast Off! // One // Two // " |
Finally, the for...in loop accesses other ergodic properties in addition to the array elements. As we mentioned in the previous article, we can add additional attributes to the array variable. Such operations can also lead to unpredictable consequences:
12345678910111213141516171819202122 |
var tMinus = [
"Two"
,
"One"
,
"Blast off!"
];
tMinus.announcer =
"Morgan Freeman"
; var countdown =
""
;
for (
var step
in tMinus) {
if (tMinus.hasOwnProperty(step)) {
countdown += tMinus[step] +
"n"
;
}
}
console.log(countdown);
// => "Two
// One
// Blast Off!
// Morgan Freeman
// "
|
This shows that when you need to iterate over an array element, you should use a for loop or an array object's built-in iterative functions (such as foreach, Map, and so on) instead of for...in loops.
Problems with in loops and arrays in JavaScript