我想了解这背后的原因:
var a = new Array(3);
var b = a.map(function () {
return 'b';
});
结果
a: [ , , ]
b: [ , , ]
当我希望 b 产生 ['b', 'b', 'b']
时。
在进一步调查中,我发现如果我要执行 a.push('a')
,我会有 [, , , 'a']
.
在 map 函数之后,b
将变为 [, , , 'b']
。
这是怎么回事?为什么这些分配的单元格的行为与初始化不同?我原本希望它的行为就像它是数组文字时那样,[undefined, undefined, undefined].map(fn)
Array.map() 不会为未定义值的索引调用回调。
来自 MDN 文档:
map calls a provided callback function once for each element in an
array, in order, and constructs a new array from the results. callback
is invoked only for indexes of the array which have assigned values;
it is not invoked for indexes that are undefined, those which have
been deleted or which have never been assigned values.