一文搞懂JavaScript数组中最难的数组API——reduce()
前面我们讲了数组的一些基本方法,今天给大家讲一下数组的reduce(),它是数组里面非常重要也是比较难的函数,那么这篇文章就好好给大家介绍下reduce函数。
还是老样子,我们直接在应用中学习,直接上例子。让我们先定义一个包含几个对象的数组,注意观察下这个数组,可以看到里面有两个对象的age都是30。(下面会用到)
| |
// 一个包含几个人物对象的数组。 |
| |
const people = [ |
| |
{ name: "John", age: 20 }, |
| |
{ name: "Jane", age: 22 }, |
| |
{ name: "Joe", age: 23 }, |
| |
{ name: "Jack", age: 24 }, |
| |
{ name: "Jackson", age: 30 }, |
| |
{ name: "Jeff", age: 30 }, |
| |
] |
1.求数组中所有对象的年龄和
通过数组的reduce方法可以很方便的实现求和。reduce方法有两个参数,第一个参数是一个回调函数,第二个参数是初始值。下面就讲下这两个参数,回调函数,有四个参数,函数体处理自己的逻辑。第二个参数,它的值决定回调函数第一个参数的初始值。重点就是这个初始值。(文末会详细介绍这几个参数)
| |
// 注意init 什么类型 res就是什么类型的 |
| |
// res的初始值为0 ,求和所以得从0开始 |
| |
const sum = people.reduce((res, cur) => res+cur.age, 0) |
| |
console.log(`结果:${sum}`); // 结果:149 |
| |
// 如果我们把初始值设为100 那么结果应该是149+100了 |
| |
const sum = people.reduce((res, cur) => res+cur.age, 100) |
| |
console.log(`结果:${sum}`); // 结果:249 |
2.按照年龄分组(比如上面有两个人都是30岁,那么他们应该分在一起)
| |
const sum = people.reduce((res, cur) => { |
| |
// console.log(res,cur); |
| |
const age = cur.age |
| |
if (res[age] == null) { |
| |
// 这里需要使用[]动态获取age值 , 用.age会有不一样的效果 |
| |
res[age] = [] |
| |
} |
| |
// 通过push插入值 |
| |
res[age].push(cur.name) |
| |
return res |
| |
}, {}) |
| |
code1.png |
3.将数组对象转化为对象,name为key ,age为value
| |
// 写法1 |
| |
const sum = people.reduce((res, cur) => { |
| |
const name = cur.name |
| |
res[name]=cur.age |
| |
return res |
| |
}, {}) |
| |
// 写法2 解构返回值 化简 |
| |
const sum = people.reduce((res, cur) => ({ |
| |
...res, |
| |
[cur.name] : cur.age |
| |
}), {}) |
| |
// 写法3 回调方法的第二个参数也可以解构 |
| |
const sum = people.reduce((res, { name, age }) => ({ |
| |
...res, |
| |
[name] : age |
| |
}), {}) |
| |
// 结果都是一样的 |
| |
console.log(sum) |
| |
image.png |
4.最后看下各个参数打印的结果,以及不写定义初始值的情况
| |
// 1.定义初始值 |
| |
const sum = people.reduce((res, cur, index, array) => { |
| |
console.log('
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/webdev/292736.html
JavaScript 承诺 – 现代 JS
上一篇
2022年11月7日 14:49
|