如果你想填充一个数组,你可以使用Array(5).fill()
然后这些方法将按预期工作——请参阅 aasha7 的替代相关答案。较旧的预填充方法包括:
Array.apply(null, new Array(5)).map(function() { return 0; });
// [ 0, 0, 0, 0, 0 ]
经过一番阅读后评论中链接的帖子 https://stackoverflow.com/questions/18947892/creating-range-in-javascript-strange-syntax/18949651#18949651,我发现这也可以写成
Array.apply(null, {length: 5}).map(function() { return 0; });
然而,尝试使用.map
对未定义的值不起作用。
x = new Array(10);
x.map(function() { console.log("hello"); });
// so sad, no "hello"
// [ , , , , , , , , , ]
.map
将跳过未定义的值:(