Array constructor not working as expected
This question already has an answer here:
From the MDN: this returns a new JavaScript array with length set to that number
The Array created by new Array(n)
does not have any elements, only a length. That's why you can't map the (not existing) elements.
map
skips over undefined elements, by design.
From the documentation:
callback
is invoked only for indexes of the array which have assigned values
There are many questions here on SO related to this topic, and providing ways to create arrays that map will operate on all elements of, such as
new Array(3) . fill() . map(...
to take just one example, using the new Array#fill method.
除了CodeiSirs答案之外的一个例子:
// foo and bar are identical. They are arrays with length 3 and no indices.
var foo = new Array(3);
var bar = [];
bar.length = 3;
console.log(foo);
console.log(bar);
// This is different. It has 3 indices with the value undefined.
var pez = [undefined, undefined, undefined];
console.log(pez);
链接地址: http://www.djcxy.com/p/89706.html
上一篇: 为什么Visual Studio的设计器与我在运行时看到的相符?
下一篇: 数组构造函数不按预期工作