2016-03-08 71 views
2

我们都知道数组文字和数组构造函数之间的区别很微妙,但是can be important。在引用的链接中似乎还有另一个不同之处。看看下面:数组文字和数组构造函数方法返回不同的结果

var x = new Array(5); // [undefined x 5]; 
var newArr = x.map(function() {return 'newValue'}); 
console.log(newArr); // [undefined x 5]; 

VS

var y = [undefined, undefined, undefined, undefined, undefined]; 
var newArr = y.map(function() {return 'newValue'}); 
console.log(newArr); // ['newValue', 'newValue', 'newValue', 'newValue', 'newValue']; 

我希望xy这两个是数组实例,并从.map方法返回相同的结果。看起来奇怪的是,数组x产生一个不可映射的数组,而文字y是可映射的。

为什么xy返回与.map方法不同的结果?

感谢您的任何帮助。

+0

由Array构造函数通过传入一个数字创建的数组,不能用数组方法迭代,这样的数组有长度但没有值,它们实际上是未定义的。 – adeneo

+0

http://stackoverflow.com/questions/32305179/whats-the-difference-between-undefined-undefined-and-new-array2 – Bergi

+0

@ adeneo-或者字面上没有定义。 ;-) – RobG

回答

3

MDN

地图用于在阵列中的每个元素一旦调用一个提供回调函数,为了,并构造从结果的新数组。仅对已分配值的数组的索引调用回调,其中包括未定义的。不会调用缺失的数组元素(即从未设置过的索引,这些索引已被删除或从未分配过值)。

+0

所以..我假设这是'从未设置过的索引'类别? –