Array.reduce()学习

昨天遇到的一道题:1234567890 => 1,234,567,890 要求其实就是使用逗号做千分位将数字进行分隔。

当时没想到任何方法,但是以前看到过,印象很深刻,今天就找了一下。

看到其实现方法是使用Array.reduce()方法:

var str = 1234567890 + '';
str.split('').reverse().reduce((prev,next,index) => {
   return ((index % 3) ? next : (next + ',')) + prev;
})

由于对reduce方法不够熟悉,恶补了一下,下面总结一下:

语法:Array.reduce(calback[, initValue])

reduce方法接受两个参数,第一个参数为对数组每个元素处理的回调方法,第二个参数可选,为reduce的初始值,如果没有设置初始值,则使用数组第一个元素。注意:在对没有设置初始值的空数组调用reduce方法时会报错。

回调参数callback的参数:accumulator,currentValue,currentIndex,array。

解释一下这几个参数的意思:

  accumulator:数组累计操作的返回值,是上一次成功操作的返回值或初始值。

  currentValue:当前操作的值。

  currentIndex:当前操作的索引,有初始值为0,否则为1。

  array:操作的原数组。

*回调函数第一次执行时,accumulator和currentValue的取值有两种情况:有初始值时,accumulator的取值为初始值,currentValue取值为数组第一个元素。无初始值时,accumulator的取值为数组第一个元素,currentValue取值为数组第二个元素。

下面是reduce方法的运行片段:

//无初始值
[1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
   return  accumulator + currentValue;
})
callback accumulator currentValue currentIndex array return value
first call 1(数组第一个元素) 2(数组第二个元素) 1(无初始值为1) [1, 2, 3, 4] 3
second call 3 3 2 [1, 2, 3, 4] 6
third call 6 4 3 [1, 2, 3, 4] 10
//有初始值
[1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
    return accumulator + currentValue;
}, 10)
callback accumulator currentValue currentIndex array return value
first call 10(初始值) 1(数组第一个元素) 0(有初始值为0) [1, 2, 3, 4] 11
second call 11 2 1 [1, 2, 3, 4] 13
third call 13 3 2 [1, 2, 3, 4] 16
fourth call 16 4 3 [1, 2, 3, 4] 20

一些例子:

//1.数组元素求和
[1, 2, 3, 4].reduce((a, b) => a+b); //10

//2.二维数组转化为一维数组
[[1, 2], [3, 4], [5, 6]].reduce((a, b) => a.concat(b), []) //[1, 2, 3, 4, 5, 6]

//3.计算数组中元素出现的次数
[1, 2, 3, 1, 2, 3, 4].reduce((items, item) => {
   if(item in items){
        items[item]++;
    }else{
        items[item] = 1;
    }
    return items;
},{}) //{1: 2, 2: 2, 3: 2, 4: 1}

//数组去重①
[1, 2, 3, 1, 2, 3, 4, 4, 5].reduce((init, current) => {
    if(init.length === 0 || init.indexOf(current) === -1){
        init.push(current);
    }
    return init;
},[]) //[1, 2, 3, 4, 5]
//数组去重②
[1, 2, 3, 1, 2, 3, 4, 4, 5].sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length-1] !== current){
        init.push(current);
    }
    return init;
},[]) //[1, 2, 3, 4, 5]

 

posted on 2018-03-07 16:36  薛将军  阅读(2175)  评论(0编辑  收藏  举报

导航