小心FOR IN遍历数组

From stackoverflow 查看原文

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]);
}
/**
 * 输出:
 * undefined (5次)
 * 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);
}

/**
 * 输出:
 * 5
 */
// 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);
}

/**
 * 输出:
 * 0
 * 1
 * 2
 * 3
 * 4
 * foo
 */

加一个 hasOwnProperty (它可是JavaScript中唯一一个处理属性而不查找原型链的函数) 过滤一下还是可以:

if (a.hasOwnProperty(x)){
  console.log(x);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值