我被告知不要for...in在JavaScript中使用数组.为什么不?
我刚刚经历了最奇怪的事情,这是我实际使用的代码:
for (iter in data.List) {
console.log(iter);
}
Run Code Online (Sandbox Code Playgroud)
正如您所料,日志应该给出每行的数量(0,1,2 ......),而不是它给我这个:
0
1
2
remove
Run Code Online (Sandbox Code Playgroud)
知道我的数组只有3行
有没人有人想过这个?
我unique()在Javascript数组中添加了函数:
Array.prototype.unique = function(){
return this.filter(function(item, ind, arr){
return ind == arr.lastIndexOf(item);
});
};
Run Code Online (Sandbox Code Playgroud)
但是当我像这样迭代:
for (i in arr) { ... }
Run Code Online (Sandbox Code Playgroud)
i变得unique如此:
var arr = [1, 2, 1];
for (i in arr) {
console.log(i + " ===> " + arr[i]);
}
// 0 ===> 1
// 1 ===> 2
// 2 ===> 1
// unique ===> function () { return this.filter(function (item, ind, arr) {return ind == arr.lastIndexOf(item);}); }
Run Code Online (Sandbox Code Playgroud)
我知道我可以像这样迭代:
for (i = 0; …Run Code Online (Sandbox Code Playgroud)