小心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 o

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);
}
目录
相关文章
|
2月前
|
Java 索引
增强for循环和一般for循环的对比使用
这篇文章对比了Java中的增强for循环(for-each循环)和传统的for循环,介绍了增强for循环的优点,如简化数组或集合的遍历、提高代码的可读性和可维护性,并指出增强for循环不适用于需要修改数组或集合元素的场景。文章还提供了增强for循环的语法格式,并展示了在实际应用中如何使用增强for循环来遍历数组和数组对象。
增强for循环和一般for循环的对比使用
|
2月前
|
算法 Java
双指针在数组遍历中的应用
文章深入探讨了双指针技术在数组遍历中的应用,通过实战例子详细解释了快慢指针和首尾指针的不同用法,并提供了解决LeetCode相关问题的Java代码实现。
|
5月前
|
算法 C语言 索引
215. 数组中的第K个最大元素(时间复杂度o(n))
215. 数组中的第K个最大元素(时间复杂度o(n))
|
5月前
|
存储 C语言
【03】逆序数组
【03】逆序数组
|
5月前
|
人工智能
数组逆序
数组逆序
28 3
|
5月前
|
索引
数组下标为什么从0开始
数组下标为什么从0开始
|
10月前
遍历一维数组
遍历一维数组
47 0
|
前端开发
数组下标对应缺位问题
数组下标对应缺位问题
44 0
|
JavaScript 前端开发
遍历数组
遍历数组
65 0
|
JavaScript 前端开发 索引
For In 遍历数组
For In 遍历数组
114 0