数组遍历总结
# 数组遍历总结
# forEach()
对数组进行遍历循环,对数组中的每一项运行给定函数。可修改原数组,这个方法没有返回值。
参数:当前值,索引值,原数组
let arr = [1, 2, 3, 4, 5];
arr.forEach((item, index, array) => {
console.log(item + '|' + index + '|' + (array === arr));
});
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# filter()
过滤,不会改变原始数组,返回新数组
参数:当前值,索引值,原数组
let arr = [
{ id: 1, text: 'aa', done: true },
{ id: 2, text: 'bb', done: false }
]
let newArr = arr.filter(item => item.done);
console.log(newArr) // [{ id: 1, text: 'aa', done: true }]
let arr = [73, 84, 56, 22, 100]
let newArr = arr.filter(item => item > 80)
console.log(arr, newArr) // [73, 84, 56, 22, 100], [84, 100]
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# map()
指“映射”,对数组中的每一项运行给定函数,返回新数组。
参数:当前值,索引值,原数组
let arr = [1, 2, 3, 4, 5];
let arr2 = arr.map( function( item, index, array ){
return item * item;
});
console.log(arr); // [1, 2, 3, 4, 5]
console.log(arr2); // [1, 4, 9, 16, 25]
1
2
3
4
5
6
2
3
4
5
6
# some()
对数组中的每一项运行给定函数,如果该函数对任一项
返回true,则返回true
参数:当前值,索引值,原数组
let arr = [ 1, 2, 3, 4, 5, 6 ];
let newArr = arr.some( function( item, index, array ){
return item > 3;
})
console.log( newArr ) // true
1
2
3
4
5
2
3
4
5
# every()
对数组中的每一项运行给定函数,如果该函数对每一项
返回true,则返回true
参数:当前值,索引值,原数组
let arr = [ 1, 2, 3, 4, 5, 6 ];
let newArr1 = arr.every(( item, index, array ) => item > 3 );
let newArr2 = arr.every(( item, index, array ) => item > 0 );
console.log( newArr1, newArr2 ); // false, true
1
2
3
4
2
3
4
# for of()
可以正确响应break
、continue
和return
语句
let arr = [2, 6, 22, 45, 134]
for (let i of arr) {
if(i > 30) break;
console.log(i);
}
// 2, 6, 22
1
2
3
4
5
6
2
3
4
5
6
# for()
最基本的方法,使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组较大时优化效果才会比较明显。
//使用变量缓存临时数组
for(let i = 0; i < arr.length; i++){
//执行代码块
console.log(i)
}
1
2
3
4
5
2
3
4
5