JavaScript里reduce的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33603809/article/details/89845851

简单得说,reduce是数组的方法

array.reduce((total, current, index, arr) => {
	// 操作
}, initialValue);

接下来直接看实例吧:
1.通常用法

const array = [1, 2, 3];
const init = 0;
const total =  array.reduce((total, curr, index, arr) => {
	// total是指上次返回的数据,curr是当前元素,index为索引,arr是当前元素
	return total += curr;
}, init); // 6

因为init是数字类型,所以arr.reduce返回的也是一个数字,并且没有对array做任何处理。

2.接下来我们看它如何起到修改当前数组的作用

// 一般我们拿到的都是一个对象数组
const object = [{
    name: 'a‘,
	sex: 'girl',
	age: 11
}, {
	name: 'b‘,
	sex: 'girl',
	age: 12
}, {
	name: 'c‘,
	sex: 'girl',
	age: 13
}, {
	name: 'd‘,
	sex: 'girl',
	age: 14
}];

// 如果name=a,我们加一个属性work: ‘IT’

object.reduce((total, curr, index, arr) => {  // index arr可以省略
	if (curr.name === 'a') {
		Object.assign(curr, { work: 'IT' });
	}
}, []);

这样就可以达到map+修改的作用了(map只做遍历,不会修改原来数组)

更多的用法请参考:https://www.jianshu.com/p/e375ba1cfc47

猜你喜欢

转载自blog.csdn.net/qq_33603809/article/details/89845851
今日推荐