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/55896553/

相关文章:

Python - 确定井字游戏的赢家

javascript - 答案不会显示在消息框中

javascript - 在 Angular 中解析 n 级深度 JSON

javascript - 使用 javascript 检测黑白棋盘上的空白位置

javascript - 如何生成序列的每个排列的数组(具有重复项)?

c++ - 为什么我的模板元代码比 for 循环慢?

javascript - 四舍五入到最接近的刻钟 - JavaScript

javascript - 从具有加权元素的数组中获取随机元素

c - 数组索引效率(特别是临时变量)

java - 尝试显示整数因子,但遇到困难