操作数组方法
记录一下自己常用到的操作数组的方法
1.forEach()
遍历数组 在回调函数中对原数组的每个成员进行修改(不用 return)
方法接收一个回调函数 回调函数接收两个参数 第一个是遍历的当前元素 第二个是元素的索引
javascript
const arr = [
{
name: '张三'
},
{
name: '李四'
},
{
name: '王五'
}
]
//遍历 arr 数组然后给每个对象元素中添加一个 id 属性 值为索引值
arr.forEach((item, index) => {
item.id = index
})
console.log(arr);
2.reduce()
遍历数组中每个元素进行迭代操作,累加、累乘之类(在回调中需要 return 每次迭代完成的值 为下一次迭代使用)
方法接收两个参数 第一个是回调函数 第二个是迭代的初始值
回调中接收两个参数 第一个是每次迭代完成的值 第二个是遍历的当前元素
javascript
const arr = [
{
name: '张三',
num: 1
},
{
name: '李四',
num: 2
},
{
name: '王五',
num: 3
}
]
//遍历 arr 数组根据每个对象元素中中的 num 属性 进行累加迭代
const finaltotal = arr.reduce((total, item) => {
return total + item.num
}, 0)
console.log(finaltotal);