javascript - 为什么使用 "for...in"进行数组迭代是一个坏主意?

标签 javascript arrays loops for-loop iteration

我被告知不要在 JavaScript 中将 for...in 与数组一起使用。为什么不呢?

最佳答案

原因是一个构造:

var a = []; // Create a new empty array.
a[5] = 5;   // Perfectly legal JavaScript that resizes the array.

for (var i = 0; i < a.length; i++) {
    // Iterate over numeric indexes from 0 to 5, as everyone expects.
    console.log(a[i]);
}

/* Will display:
   undefined
   undefined
   undefined
   undefined
   undefined
   5
*/

有时可能与其他完全不同:

var a = [];
a[5] = 5;
for (var x in a) {
    // Shows only the explicitly set index of "5", and ignores 0-4
    console.log(x);
}

/* Will display:
   5
*/

还要考虑JavaScript库可能会执行类似的操作,这将影响您创建的任何数组:

// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;

// Now you have no idea what the below code will do.
var a = [1, 2, 3, 4, 5];
for (var x in a){
    // Now foo is a part of EVERY array and 
    // will show up here as a value of 'x'.
    console.log(x);
}

/* Will display:
   0
   1
   2
   3
   4
   foo
*/

关于javascript - 为什么使用 "for...in"进行数组迭代是一个坏主意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086358/

相关文章:

ios - RaptureXML 迭代 :usingBlock warning and crash

java - 在单独的方法中操作数组

c - 为什么C中的while循环突然终止

Javascript 幻灯片不滑动

javascript - 我收到引用错误 :checkout not defined

javascript - 计算数组 javascript 中单词出现的次数

arrays - 使用数组切片中的部分和行填充表

javascript - 在javascript中循环调用函数

html中的Javascript写入文件

javascript - $.ajax 调用后业务逻辑的推荐位置