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'];
我希望x
和y
这两个是数组实例,并从.map
方法返回相同的结果。看起来奇怪的是,数组x
产生一个不可映射的数组,而文字y
是可映射的。
为什么x
和y
返回与.map
方法不同的结果?
感谢您的任何帮助。
由Array构造函数通过传入一个数字创建的数组,不能用数组方法迭代,这样的数组有长度但没有值,它们实际上是未定义的。 – adeneo
http://stackoverflow.com/questions/32305179/whats-the-difference-between-undefined-undefined-and-new-array2 – Bergi
@ adeneo-或者字面上没有定义。 ;-) – RobG