提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
reduce和reduceRight都是JS数组的API。会将上一次计算结果带到下一次计算中,可以用来累加。看一下官方解释吧~
reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
reduceRight() 方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。
reduce和reduceRight都是一样的,reduce是从做开始计算,reduceRight是从右开始计算。
写reduce之前,先分析一下他的功能:
1、接受一个函数(必传),一个初始值(可选)
2、每一次计算都会将先前元素计算结果作为参数返回
3、将其结果汇总为单个返回值
代码如下(示例):
Array.prototype.myReduce = function (callback, agr){
// 判断传入回调函数是否是一个function
if(typeof callback != "function"){
throw new TypeError (callback + 'is not a function')
}
let _this = this
// 判断是否正确传入的数组长度是否是空数组
if(_this.length < 1){
throw new TypeError (agr + 'array error')
}
let length = _this.length
// 判断是否传入初始值,如果传入初始值,那么prev的初始值就是arg,不然就是数组的第一个值
let prev = agr
if(prev === undefined){
prev = _this[0]
length = length -1
}
// 对数组循环
for(let i = 0; i < length; i++){
// 判断是否有传入初始值,有就从数组0开始
if(agr!=undefined){
prev = callback(prev, _this[i], i, this)
}else{
// 没有传入初始值,初始值为数组的第一个值,那么计算就从数组的第二个值开始
prev = callback(prev, _this[i+1], i+1, this)
}
}
return prev
}
写reduce之前,先分析一下他的功能:
1、接受一个函数(必传),一个初始值(可选)
2、每一次计算都会将先前元素计算结果作为参数返回
3、将其结果汇总为单个返回值
4、与reduce不同他是从右往左计算的
代码如下(示例):
// 实现一个reduceRight
Array.prototype.myReduceRight = function(callback, initValue){
//判断callback是否是一个function
if(typeof callback != 'function'){
throw new TypeError (callback + 'is not a function')
}
//判断传入数组是否是空数组
let _this = this
let length = _this.length - 1
if(length < 1){
throw new TypeError (_this + 'type ERR')
}
// 判断是否传入了初始值,如果没有传入初始值
let prev = initValue
if(initValue == undefined){
prev = _this[length]
length = length - 1
}
// 从右往左开始,所以从最后一位开始
for(let i = length; i >= 0; i--){
// 判断是否有传入初始值,有就从数组0开始
prev = callback(prev, _this[i], i, this)
}
return prev
}
以上就是手写reduce和reduceRight的代码了。