我试图理解“空”稀疏数组之间的区别(例如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
密集阵列 http://www.2ality.com/2012/06/dense-arrays.html
如果我对其中任何一个执行 console.log ,结果是:
[undefined, undefined, undefined]
如果我循环每个数组以将其与另一个数组进行比较,它们将严格匹配:
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'
但是,如果我使用.forEach
(or map
, reduce
等),那么回调函数将永远不会在稀疏数组上被调用,但会在密集数组上被调用 3 次:
sparse.forEach(function(val,i){
console.log(i +':'+ val);
});
// Nothing. No-op.
dense.forEach(function(val,i){
console.log(i +':'+ val);
});
// '0:undefined'
// '1:undefined'
// '2:undefined'
所以我的问题是:
- 如果它们都具有相同的长度、索引和值,那么如何一个可迭代而另一个不可迭代?
- 差异的原因是什么?
- 确定数组是稀疏还是密集的最佳方法是什么?