遍历

总结

  • 从遍历数组的效率上来讲
    普通for循环 >= forEach > for-of > for-in
  • forEach 也叫增强for循环,是JavaScript5开始内置的循环方法。并不是说foreach就比for更好用,foreach适用于循环次数未知,或者计算循环次数比较麻烦情况下使用效率更高,但是更为复杂的一些循环还是需要用到for循环效率更高
  • for-in 循环实际是为循环”enumerable“对象而设计(一般用于遍历对象不用于循环数组)
  • for-of 是JavaScript6里引入了一种新的循环方法,它既比传统的for循环简洁,同时弥补了forEach和for-in循环的短板

数组

let array = [1, 2, 3, 3, 4]

传统/普通for循环

最原始,也是性能最好的循环

for (let index = 0; index < array.length; index++) {
    const element = array[index];
    console.log(element);
}
/*
1
2
3
3
4
*/

forEach

写法简洁,推荐使用

轻量级数据的时候性能和for循环一致,涉及到复杂算法的时候还是使用普通for循环好

array.forEach((item, index) => {
    console.log(item, index);
})
/*
1 0
2 1
3 2
3 3
4 4
*/

for-in

一般用来遍历对象属性

let obj = {
    a: '1',
    b: '2'
}
for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
        const element = obj[key];
        console.log('element = ', key, element);
    }
}
/*
element =  a 1
element =  b 2
*/
let arrObj = [
    {a: 'obj1'},
    {a: 'obj2'},
    {a: 'obj3'}
]
for (const key in arrObj) {
    if (arrObj.hasOwnProperty(key)) {
        const element = arrObj[key];
        console.log('element = ', key, element);
    }
}
/*
element =  0 { a: 'obj1' }
element =  1 { a: 'obj2' }
element =  2 { a: 'obj3' }
*/

for-of

for (const iterator of arrObj) {
    console.log(iterator)
}
/*
{ a: 'obj1' }
{ a: 'obj2' }
{ a: 'obj3' }
*/

map

forEach和map循环的区别:forEach没有返回值,即使你给出return也不管用,map会返回一个新数组给你,原数组不会发生改变。

let arr2 = array.map((item, index) => {
    return (item + 2)
})
console.log(array);
console.log(arr2);
/*
[ 1, 2, 3, 3, 4 ]
[ 3, 4, 5, 5, 6 ]
*/

filter

从字面上看就是过滤筛选的意思

let arr3 = array.filter(item => item === 3)
console.log(array);
console.log(arr3);
/*
[ 1, 2, 3, 3, 4 ]
[ 3, 3 ]
*/

some

用于检测数组中的元素是否满足条件

let arr4 = array.some(item => item === 3)
console.log(array);
console.log(arr4);
/*
[ 1, 2, 3, 3, 4 ]
true
*/

every

检测数组所有元素是否都满足,只要有一项不满足就是false

let arr5 = array.every(item => item >= 1)
console.log(array);
console.log(arr5);
/*
[ 1, 2, 3, 3, 4 ]
true
*/
let arr5 = array.every(item => item > 1)
console.log(array);
console.log(arr5);
/*
[ 1, 2, 3, 3, 4 ]
false
*/

find

检查数组中符合条件的第一个元素并返回

要注意的是find函数在查找时,一旦数组中的某一个元素符合查找条件,则立即返回

find和some很类似,都是寻找符合条件的,有一个就可以 不过some进去搜罗了一圈回来如果有符合条件的就返回true,而find是将符合条件的那条数据返回出来(返回第一个符合条件的对象)。

let arr6 = array.find(item => item === 8)
console.log(array);
console.log(arr6);
/*
[ 1, 2, 3, 3, 4 ]
undefined
*/
let arr6 = array.find(item => item === 3)
console.log(array);
console.log(arr6);
/*
[ 1, 2, 3, 3, 4 ]
3
*/

你可能感兴趣的:(遍历)