<分区>
我想使用数组构造函数 Array()
快速构造一个长度为 n
的数组,然后循环生成的数组。
根据 MDN's docs :
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a RangeError exception is thrown.
据推测,执行 Array(5)
会创建一个长度为 5 的数组,它会这样做。
var arr = new Array(5);
console.log(arr); // [undefined x 5]
console.log(arr.length); // 5
但是,当我尝试遍历结果数组并注销值或索引时,没有任何反应。
arr.forEach(function(v, i) { console.log(v, i); });
// nothing logs to the console
或者,如果我使用数组文字,并尝试循环遍历这些值,它会按预期记录:
[undefined, undefined].forEach(function(v, i) { console.log(v, i); });
// undefined 0
// undefined 1
为什么我不能遍历由 Array 构造函数创建的数组?
This answer解释了 map
出现的一些浏览器奇怪现象,例如:
arr.map(function(v, i) { return i; }) // returns [undefined x 5]
但我特别感兴趣的是,为什么 forEach
循环根本不对这些值进行迭代。