gpt4 book ai didi

javascript - forEach 未初始化的数组

转载 作者:行者123 更新时间:2023-11-29 21:30:13 24 4
gpt4 key购买 nike

<分区>

具有未初始化值的数组 例如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>

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com