【JS】遍历数组常用的八种方法

98 阅读2分钟

八种方法分别为:forEach、map、some、every、find、findIndex、filter、reduce

初始数组

const arr = [{ 
    id: '01', val: 50 }, { 
    id: '02', val: 80 }, { 
    id: '03', val: 100 }, { 
    id: '04', val: 150 }, { 
    id: '05', val: 200 }, { 
    id: '06', val: 250 
}];

forEach和map区别为:forEach没有返回值(forEach是没有返回值的, 即便加上return也没有用。return无法停止循环),map有返回值。

let arrForEach = arr.forEach(item => { return item.val += 50 }) 
//undefined

let arrMap = arr.map(item => { return item.val += 20 }) 
//[120, 150, 170, 220, 270, 320]

some判断是否有一个符合条件,有则返回 true 并停止全部遍历(性能优良)

let arrSome = arr.some(item => { return item.val > 100 }) 
//true

every判断是否全部符合条件,是则返回 true,其中有不符合的返回false

参数描述
item必须。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
let arrEveryTwo = arr.every(item => { return item.val >= 50 }) 
//true

let arrEveryOne = arr.every(item => { return item.val > 100 }) 
//false

find判断是否符合条件。有则返回第一个符合条件的对象

let arrFind = arr.find(item => { return item.val > 100 }) 
//{id: '04', val: 150}

findIndex判断是否符合条件,有则返回第一个符合条件对象的索引。

let arrFindIndex = arr.findIndex(item=>{ return item.val > 100 }) 
//3

filter方法筛选过滤出符合条件的对象数组。返回一个新的对象数组,并不会改变原数组。

let arrFilter = arr.filter(item => { return item.val > 100 }) 
//[{id: '04', val: 150},{id: '05', val: 200},{id: '06', val: 250}]

reduce遍历数组对象可将某个值叠加返回(计算总价可使用)

reduce()方法接收一个回调函数作为第一个参数,回调函数又接受四个参数,分别是:

参数描述
sum必需。初始值, 或者计算结束后的返回值。
item必需。当前元素
index可选。当前元素的索引
arr可选。当前元素所属的数组对象。

第二个参数

参数描述
initialValue可选。传递给函数的初始值

reduce()方法返回的是最后一次调用回调函数的返回值;

let arrReduce = arr.reduce((sum, item) => { return sum += item.val}, 0) 
//830