*****for in数组遍历的坑*****
对数组使⽤for in遍历,我们会遇到⼀个很严重的bug,那就是for in会遍历到数组添加到原型链上的属性,也就是说作用于数组的for-in循环体除了遍历数组元素外,还会遍历自定义的属性。
1. 当我们对数组使用for in遍历时
Array.prototype.istrue = function(value) {return true;}
var a = [1,2];
for(var i in a) {
console.log(a[i]);
}
输出结果:
1
2
function(value) {return true;}
所以,数组的遍历中不推荐使用for in,而使用forEach或是for of代替,由于forEach只能遍历索引数组,而for of能遍历数字下标的一切,即索引数组、类数组对象、字符串,所以我们⼀般遍历数组推荐使用for of代替forEach、for in。注:上⾯的i变量是string,并不是number
2. ⼀般的,我们对对象的遍历通常使用for in
var a = {"x":1,"y":2};
for(var i in a) {
console.log(a[i]);}
输出结果:
1
2
3. 如果使⽤了for in遍历数组,就⽤hasOwnProperty来规避遍历到原型链上的属性或⽅法
Array.prototype.istrue = function(value) {return true;}
var a = [1,2];
for(var i in a) {
if(a.hasOwnProperty(i){
console.log(a[i]);
})
}
输出结果:
1
2