数组遍历方法归纳

(1)for ... in ...

for...in 语句用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)

// 遍历数组
var a = [1, 2, 3, 4, 5];
for(let i in a) {
    console.log(i)      // 得到的是 索引 or 属性 or 键  0 1 2 3 4
}
console.log(i)      //  not defined

// 遍历对象
var obj = {x: 1, y: 2, z: 3};
for(let o in obj) {
    console.log(o)      // x y z
}

(2)for ... of ...

for...of 语句用于遍历数组的值(对数组的值进行循环操作)

// 遍历数组
var a = [1, 2, 3, 4, 5];
for(var i of a) {
    console.log(i)      // 得到的是数组的值 1 2 3 4 5
}
console.log(i)     // 5

#### ⚠️注意:for ... of ... 不可用于对象,会报错 obj is not iterable (不可迭代的)
<image src="https://img2018.cnblogs.com/blog/1649251/201911/1649251-20191106193337102-1760407953.png" width="500"></image>

###(3)for(let i = 0; i < array.length; i++)
>for(let i = 0; i < array.length; i++) 语句用于索引指向循环遍历数组

var arr = ['x', 'y', 'z'];
for(var i = 0; i < arr.length; i++) {
console.log('index: ', i, ' item: ', arr[i])
}
/*
index: 0 item: x
index: 1 item: y
index: 2 item: z
*/
```

(4)filter方法

filter() 方法对数组中的每一项运行给定函数( callback ),通过遍历筛选返回符合条件( 筛选结果 为 true )的数组,有三个参数(item, index, array),返回一个新数组,不会改变原数组

(5)

猜你喜欢

转载自www.cnblogs.com/Pecci/p/11808333.html