【问题标题】:forEach with uninitialized array [duplicate]具有未初始化数组的 forEach [重复]
【发布时间】:2016-08-08 05:04:22
【问题描述】:

具有未初始化值 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>

【问题讨论】:

  • 有任何理由使用(array).forEach(.. 而不是array.forEach(... 吗?

标签: javascript arrays foreach iteration


【解决方案1】:

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

这就是规范。

forEach 及其兄弟会忽略稀疏数组中的“洞”。如需更多信息,请参阅this blog post

来自MDN

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

spec 说了同样的话。

【讨论】:

  • Array.apply(null, Array(3)) 正是我想要的。谢谢!
  • 如果你想填补空缺,如果你有Array#fill 可用,Array(3).fill() 也可以。
  • 我使用的是旧版本的节点。它似乎不存在。 :(
  • fwiw,我投票决定重新打开问题(错误),试图查看重复的问题。没有看到顶部的横幅,因为它在首屏上方。我确实搜索了这个问题,但没有找到任何东西。无论如何感谢您的回答。博客很棒。考虑到元素的删除,这是非常有意义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2018-09-19
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
相关资源
最近更新 更多