具有未初始化数组的forEach
forEach with uninitialized array
具有未初始化值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()
为数组中存在的每个元素执行一次所提供的回调
说明书上也有同样的内容。
相关文章:
- 如果数组仍在执行,async.forEach()将运行我添加到数组中的新元素
- 需要帮助比较数组内的值,使用forEach循环
- 敲除foreach数字数组
- 使用从forEach循环中提取的国家代码从数组中获取国家名称
- 在JavaScript中,用forEach乘以数组的所有元素
- 将 PHP 值 (ACF) 添加到 foreach 循环中的 Javascript 数组中
- 为什么“.forEach”适用于密集数组,而不适用于稀疏数组
- 具有未初始化数组的forEach
- 对可观察数组foreach的更新删除了格式化knockoutjs
- PHP和Ajax在回调和返回数组中使用foreach循环
- forEach的奇怪数组构造函数行为
- JSON对象中的数组属性通过foreach更新-更新所有键
- 如何在不选择模式配置参数的情况下,使用mongoose在MongoDB模式实例化中的关联数组/对象中执行foreach
- 在 Javascript 中使用 ForEach 填充数组对象时,我是否需要定义一个数组对象
- 为什么以下 forEach 数组循环未返回未定义
- Javascript Foreach 循环遍历对象数组
- 为什么当我使用 Angular 在 forEach 循环中时,我无法访问工厂中的数组
- 如何从 javascript 中的 foreach 循环中删除特定的数组元素
- forEach数组javascript不完整
- javascript foreach数组,并用逗号和空格分隔,显示为字符串