JavaScript reduce() 方法

this.data = this.list.reduce((total,per)=>{
  total.push({
    name:per.keyWrdDsc, 
    value:per.num1
  }}
  return total;
},[]);


this.config = ['bar','line','per'];
this.config.reduce((total,per)=>{
  total[per] = true;
},{})

res = {bar:true,line:true,pei:true}

实例

计算数组元素相加后的总和:

var numbers = [65, 44, 12, 4];
function getSum(total, num) {
  return total + num;
}
function myFunction(item) {
  document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}

输出结果:

125

 

 

 

前言
reduce() 方法对数组中的每个元素执行一个由您提供的reduce函数(升序执行),将其结果汇总为单个返回值。reduce方法可做的事情特别多,就是循环遍历能做的,reduce都可以做,比如数组求和、数组求积、数组中元素出现的次数、数组去重等等。

语法
arr.reduce(function(prev,cur,index,arr){
...
}, init);

参数:

prev 必需。累计器累计回调的返回值; 表示上一次调用回调时的返回值,或者初始值 init;
cur 必需。表示当前正在处理的数组元素;
index 可选。表示当前正在处理的数组元素的索引,若提供 init 值,则起始索引为- 0,否则起始索引为1;
arr 可选。表示原数组;
init 可选。表示初始值。

 

 

对对象的属性求和
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
let result = people.reduce((a,b) =>{
a = a + b.age;
return a;
},0)

console.log(result) // - 结果:61

分析:
 这里主要就是利用reduce第一个参数是迭代,可以通过初始化这个参数的数据类型,达到想实现的效果。

总结
reduce() 是数组的归并方法,与 forEach()、map()、filter()等迭代方法一样都会对数组每一项进行遍历,但是reduce() 可同时将前面数组项遍历产生的结果与当前遍历项进行运算,这一点是其他迭代方法无法企及的。

 


原文链接:https://blog.csdn.net/qq_38970408/article/details/121018660

posted @ 2020-12-28 17:31  炽橙子  阅读(285)  评论(0编辑  收藏  举报