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(比较奇怪)。
————————————————
版权声明:本文为CSDN博主「Great_Eagle」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Great_Eagle/article/details/81546437

发布了235 篇原创文章 · 获赞 88 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/qq_34629352/article/details/105249053
今日推荐