数组reduce()和reduceRight()方法

reduce()方法

reduce() 方法接收一个函数 callback 作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。

语法

array.reduce(callback[, initialValue])

reduce() 方法接收 callback 函数,而这个函数包含四个参数:

function callback(accumulator, currentValue, currentIndex, array){}
  • accumulator : 上一次调用回调返回的值,或者是提供的初始值(initialValue)
  • currentValue : 数组中当前被处理的数组项
  • currentIndex : 当前数组项在数组中的索引值
  • array : 调用 reduce() 方法的数组
    initialValue 作为第一次调用 callback 函数的第一个参数。

reduce() 方法为数组中的每一个元素依次执行回调函数 callback,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce() 的数组。

回调函数第一次执行时,accumulatorcurrentValue 可以是一个值,如果 initialValue 在调用 reduce() 时被提供,那么第一个 accumulator 等于 initialValue ,并且 currentValue 等于数组中的第一个值;如果 initialValue 未被提供,那么 accumulator 等于数组中的第一个值,currentValue 等于数组中的第二个值。

var arr = [0,1,2,3,4];

arr.reduce(function (accumulator, currentValue, currentIndex, array) {
    return accumulator+ currentValue;
}); // 10

reduceRight()方法

reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。

reduceRight() 首次调用回调函数 callback 时,accumulatorcurrentValue 可以是两个值之一。如果调用 reduceRight() 时提供了 initialValue 参数,则 accumulator 等于 initialValuecurrentValue 等于数组中的最后一个值。如果没有提供 initialValue 参数,则 prevValue 等于数组最后一个值, currentValue 等于数组中倒数第二个值。

var arr = [0,1,2,3,4];

arr.reduceRight(function (accumulator, currentValue, currentIndex, array) {
    return accumulator + currentValue;
}); // 10

练习:不要使用JavaScript内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数:

'use strict';

function string2int(s) {
    return s.split("").map(function(item) {
        return item * 1;
    }).reduce(function(x, y) {
        return x * 10 + y;
    });
}
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值