遍历方法

97 阅读1分钟

1.for...in:数组/类数组/对象/字符串;

缺点:
    1.遍历的下标是字符串数字;
    2.遍历的还包裹原型上的属性,不只是数组本身;
var arr = [1,2,3]
for (let index in arr) {
    let res = index + 1 // 遍历的下标是字符串数字;
    console.log(res) // 01 11 21
}

var arr = [1,2,3]
Array.prototype.a = 123
for (let index in arr) {
    let res = arr[index]
    console.log(res) // //1 2 3 123
}
注:使用hasOwnProperty()判断是否在对象的实例属性:arr.hasOwnProperty(index);

2.for...of:ES6新出,数组/字符串/map/set/拥有iterator(迭代器对象)的集合;

缺点:不能直接遍历对象/类数组;
var arr = [1,2,3]
Array.prototype.a = 123
for (let value of arr) {
    console.log(value) //1 2 3,仅遍历组数本身
}

// 遍历对象:使用Object.keys();
var myObject= { a:1, b:2, c:3 }
for (var key of Object.keys(myObject)) {
    console.log(key + ": " + myObject[key]); //a:1 b:2 c:3
}