具有未初始化数组的forEach

forEach with uninitialized array

本文关键字:forEach 数组 初始化      更新时间:2023-09-26

具有未初始化值e.g. new Array(100)的数组不会使用forEach进行迭代。长度正确。使用[undefined,undefined,...]创建数组会按预期进行迭代,但使用[,,,,,]创建数组则不会。

我想知道是否有人能向我解释一下。

var array = new Array(100),
    msg;
_init();
console.log("Array length:",array.length);
// forEach is skipped
a = ["forEach:"];
(array).forEach(function(i){
  a.push(i);
});
console.log(a.join(','));
// forEach is also skipped
a = ["forEach array without undefined:"];
([,,,]).forEach(function(i){
  a.push(i);
});
console.log(a.join(','));
// forEach is displayed
a = ["forEach normal array:"];
([undefined,undefined,undefined,undefined]).forEach(function(v,i){
  a.push(v);
});
console.log(a.join(','));
// for is displayed
a = ["for:"]
for(var i=0;i<array.length;i++){
  a.push(i);
}
console.log(a.join(','));
// array.join is displayed (even the ough the values are empty)
a = ["join:"]
a = a.concat(array)
console.log(a.join(','));
// log to target div (ignore this)
function _init(){
  console = {log:targetlog};
}
function targetlog(){
  var args = Array.prototype.slice.apply(arguments);
  $("#target").append("<div>" + args.join(" ") + "</div>")
}
span {
  outline:1px solid gainsboro;
  margin:2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>

我想知道是否有人能向我解释一下。

这就是的规格

forEach及其同类忽略了稀疏阵列中的"空穴"。有关更多信息,请参阅此博客文章。

来自MDN:

forEach()为数组中存在的每个元素执行一次所提供的回调

说明书上也有同样的内容。