我在Firefox-3.5.7/Firebug-1.5.3和Firefox-3.6.16/Firebug-1.6.2中观察到了这一点
当我开火萤火虫时:
var x = new Array(3)
console.log(x)
// [undefined, undefined, undefined]
var y = [undefined, undefined, undefined]
console.log(y)
// [undefined, undefined, undefined]
console.log( x.constructor == y.constructor) // true
console.log(
x.map(function() { return 0; })
)
// [undefined, undefined, undefined]
console.log(
y.map(function() { return 0; })
)
// [0, 0, 0]Run Code Online (Sandbox Code Playgroud)
这里发生了什么?这是一个错误,还是我误解了如何使用new Array(3)?
我发现在javascript中我不能在空数组上使用a.任何人都可以向我解释为什么会这样吗?
我在javascript中初始化了一个数组,如下所示:
var arr = new Array(10);
Run Code Online (Sandbox Code Playgroud)
当我在数组上使用a for each循环时没有任何反应:
arr.forEach(function(i) {
i = 0;
});
Run Code Online (Sandbox Code Playgroud)
结果仍然是一组未定义的值:
arr = [ , , , , , , , , , ];
Run Code Online (Sandbox Code Playgroud)
我想也许因为数组中的每个项都是未定义的,所以它甚至都不执行forEach.我认为它仍然会遍历未定义的项目.谁能解释为什么会这样?这个问题不是要求如何最有效地用零填充数组,它要求详细说明每个循环和空数组的交互.
为什么这个:
[undefined, undefined].map(function(i) { console.log(i); })
Run Code Online (Sandbox Code Playgroud)
产生预期的输出(2次undefined),但是:
(new Array(2)).map(function(i) { console.log(i); })
Run Code Online (Sandbox Code Playgroud)
不?
我试图理解'空'稀疏数组(例如new Array(3))和等效'空'密集数组(具有3个未定义条目的数组)之间的区别.
我可以用这两种方式创建一个包含3个未定义值的数组:
var sparse = new Array(3);
// or
var sparse = [,,,];
var dense = Array.apply(null, Array(3)); // See dense array link below
Run Code Online (Sandbox Code Playgroud)
如果我为其中任何一个执行console.log,结果是:
[undefined, undefined, undefined]
Run Code Online (Sandbox Code Playgroud)
如果我遍历每个数组以将其与另一个数组进行比较,它们将严格匹配:
console.log(sparse.length === dense.length);
// true
for (var i = 0; i < dense.length; i++) {
console.log(i +':'+ (dense[i] === sparse[i]));
}
// '0:true'
// '1:true'
// '2:true'
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用.forEach(或map,reduce等),那么回调将永远不会在稀疏数组上调用,但会在密集数组上调用三次:
sparse.forEach(function(val,i){
console.log(i +':'+ val);
});
// Nothing. No-op.
dense.forEach(function(val,i){
console.log(i +':'+ val);
}); …Run Code Online (Sandbox Code Playgroud) 我想n使用数组构造函数快速构造一个长度数组Array(),然后遍历生成的数组.
根据MDN的文档:
如果传递给Array构造函数的唯一参数是0到2 32 -1(含)之间的整数,则返回一个长度设置为该数字的新JavaScript数组.如果参数是任何其他数字,则抛出RangeError异常.
据推测,执行Array(5)会创建一个长度为5的数组.
var arr = new Array(5);
console.log(arr); // [undefined x 5]
console.log(arr.length); // 5Run Code Online (Sandbox Code Playgroud)
但是,当我尝试循环结果数组并注销值或索引时,没有任何反应.
arr.forEach(function(v, i) { console.log(v, i); });
// nothing logs to the console
Run Code Online (Sandbox Code Playgroud)
或者,如果我使用数组文字,并尝试循环值,它会按预期记录:
[undefined, undefined].forEach(function(v, i) { console.log(v, i); });
// undefined 0
// undefined 1Run Code Online (Sandbox Code Playgroud)
为什么我不能遍历由Array构造函数创建的数组?
这个答案解释了一些浏览器的陌生感map,例如:
arr.map(function(v, i) { return i; }) // returns [undefined x 5]
Run Code Online (Sandbox Code Playgroud)
但我特别感兴趣的是为什么forEach循环不会对值进行迭代.