js中的reduce()函数

案例

  1. 计算数组总和
var num = [1,2,3,4,5];
var res = num.reduce(function(total,num){
    return total+num;
    //return total + Math.round(num);//对数组元素四舍五入并计算总和
});
console.log(res);//15
  1. 合并二维数组
var red = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
 return a.concat(b);
}, []);
console.log(red)
VM291:4 (6) [0, 1, 2, 3, 4, 5]
  1. 统计一个数组中有多少个不重复的单词:
不用reduce时:
var arr = ["apple","orange","apple","orange","pear","orange"];
function getWordCnt(){
  var obj = {};
  for(var i= 0, l = arr.length; i< l; i++){
    var item = arr[i];
    obj[item] = (obj[item] +1 ) || 1;
  }
  return obj;
}
console.log(getWordCnt());
VM3704:14 {apple: 2, orange: 3, pear: 1}

用reduce时:
var arr = ["apple","orange","apple","orange","pear","orange"];
function getWordCnt(){
  return arr.reduce(function(prev,next){
    prev[next] = (prev[next] + 1) || 1;
    return prev;
  },{});
}
console.log(getWordCnt());
VM3704:14 {apple: 2, orange: 3, pear: 1}
  1. 对reduce的理解:
    reduce(callback,initiaValue)会传入两个变量,回调函数(callback)和初始值(initiaValue)。
    假设函数有个传入参数,prev和next,index和array。 Prev和next是你必须要了解的。
    当没有传入初始值时,prev是从数组中第一个元素开始的,next是第二个函数。
    但是当传入初始值(initiaValue)后,第一个prev将是initivalValue,next将是数组中的第一个元素。
    比如:
var arr = ["apple","orange"];
function noPassValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    return prev;
  });
}

function passValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    prev[next] = 1;
    return prev;
  },{});
}
console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());

VM415673:4 prev: apple
VM415673:5 next: orange
VM415673:4 prev: apple
VM415673:5 next: orange
VM415673:19 No Additional parameter: apple
VM415673:20 ----------------
VM415673:13 prev: {}
VM415673:14 next: apple
VM415673:13 prev: {apple: 1}
VM415673:14 next: orange
VM415673:21 With {} as an additional parameter: {apple: 1, orange: 1}

 

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值