forEach与for-in的坑爹地方

			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(比较奇怪)。

 

你可能感兴趣的:(JavaScript)