var arrCheck = new Array(100 + 1);
arrCheck[4]=undefined;
for(var i in arrCheck){
arrCheck[i]=false;
console.log(1);//1,只输出1次
}
console.log(arrCheck);//[empty × 4, false, empty × 96]
console.log(arrCheck[0]===undefined);//true
var arrCheck = new Array(100 + 1);
arrCheck[4]=undefined;
arrCheck.forEach(function(item, index, array) {
arrCheck[index] = false;
console.log(1);//1,只输出1次
});
console.log(arrCheck);//[empty × 4, false, empty × 96]
console.log(arrCheck[0]===undefined);//true
这段代码forEach和for-in只执行了1次,即 console.log(1)只执行了1次。
这是为什么呢?
答: 在所有浏览器中,forEach函数和for-in都忽略未赋值的元素。 在所有浏览器(火狐,chrome,edge)中, forEach函数和for-in都不忽略数组中值为 undefined和null的元素。但需注意,可验证未赋值的元素===undefined(比较奇怪)。