说一个小坑吧。

之前在看《JavaScript高级程序设计》的时候,看到这样一句话:“它只是对数组中的每一项运行传入的函数,这个方法没有返回值,本质上与使用for循环迭代数组一样。”(P97)

于是就测试用了一下:

var arr0 = [0,0,0,0,0];
arr0.forEach(function( item,index,array ){
  array[index] = index * 2;
});
console.log(arr0);

结果:

[0, 2, 4, 6, 8]

是对的,我又这样使用了一下:

var arr1 = new Array(5);
arr1.forEach(function( item,index,array ){
  array[index] = index * 2;
});
console.log(arr1);

结果:

[]

好像哪里不对,于是这样写:

var arr2 = new Array(5);
arr2[0] = 0;
arr2[1] = 0;
arr2.forEach(function( item,index,array ){
  array[index] = index * 2;
});
console.log(arr2);

结果:

[0, 2]

这样写呢?

var arr2 = new Array(5);
arr2[0] = 0;
arr2[1] = 0;
arr2[2] = undefined;
arr2.forEach(function( item,index,array ){
  array[index] = index * 2;
});
console.log(arr2);

结果:

[0, 2, 4]

最后在MDN上的找到这样的描述:

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).