自己动手实现一个Array.prototype.reduce?




定义和用法

reduce是数组内置的一个方法,原型链上位于Array.prototype.reduce()

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

reduce() 可以作为一个高阶函数,用于函数的 compose。

注意: reduce() 对于空数组是不会执行回调函数的。

reduce对数组累积执行回调函数,返回最终计算结果




语法

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • function(total, currentValue, currentIndex, arr)
参数描述
total必需。初始值, 或者计算结束后的返回值。
currentValue必需。当前元素
currentIndex可选。当前元素的索引
arr可选。当前元素所属的数组对象。
  • initialValue

可选。传递给函数的初始值




自己实现一个




队列实现

一般来说,这种累计操作,都是用队列。

  • 不断地对数组的前两项“取出”,对其执行目标函数,计算得到的返回值
  • 把上述返回值“填回”数组首部,作为新的 队头
  • 重复上述过程,直到数组中每一项都访问了一次
  • 返回最终结果
Array.prototype.myReduce = function(func, initialValue) {
    if (typeof func !== "function") {
        throw new TypeError("arguments[0] is not a function");
    }
    
    // 拿到当前调用的数组
    let initialArr = this;

    // 深拷贝
    let arr = initialArr.concat();

    // 加入到队头中
    if ( initialValue !== null ) 
        arr.unshift( initialValue);
        console.log(arr)
    
    let index, newValue;

    while (arr.length >= 2) {
        index = initialArr.length + 1 - arr.length ;
        newValue = func.call(null, arr[0], arr[1], index, initialArr);

        // 用 splice 实现替换
        arr.splice(0, 2, newValue);
        console.log(arr)
    }
    console.log(arr);

    return newValue;
};

let testArr = [1, 2, 3, 4, 5]


let result = testArr.myReduce(
    (prev, next, index) => {
        prev += next;
        console.log(index)
        return prev;
    },
    5,
)
console.log(result)

输出如下

[ 5, 1, 2, 3, 4, 5 ]
0
[ 6, 2, 3, 4, 5 ]
1
[ 8, 3, 4, 5 ]
2
[ 11, 4, 5 ]
3
[ 15, 5 ]
4
[ 20 ]
[ 20 ]
20



递归实现

Array.prototype.myReduce = function (cb, initialValue) {
    if (typeof cb !== "function") {
        throw new TypeError("arguments[0] is not a function");
    }

    const array = this
    const [head, ...tail] = array
    const startIndex = initialValue ? -1 : 0

    if (initialValue !== null) {
        return reduceHelper(cb, initialValue, startIndex, array)
    }
    return reduceHelper(cb, head, startIndex, tail)
}

function reduceHelper(func, accumulator, index, array){
    // 递归终止条件
    if (array.length === 0)
        return accumulator

    const [head, ...tail] = array

    index++;

    return reduceHelper(
        func,
        func(accumulator, head, index, array),
        index,
        tail
    )
}





let testArr = [1, 2, 3, 4, 5]


let result = testArr.myReduce(
    (prev, next, index) => {
        prev += next;
        console.log(index)
        return prev;
    },
    5,
)
console.log(result)



遍历数组实现

Array.prototype.myReduce = function (callback, initialValue) {
    if (typeof callback !== "function") {
        throw new TypeError("arguments[0] is not a function");
    }

    const array = this;
    console.log(this);
    console.log(initialValue);

    let accmulator;
    let startIndex;

    if (initialValue !== null) {
        accmulator = initialValue;
        startIndex = 0
    } else {
        accmulator = array[0];
        startIndex = 1
    }

    console.log("初始累计值:" + accmulator);
    console.log("初始索引值:" + startIndex);

    for (let i = startIndex; i <= array.length - 1; i++) {

        accmulator = callback(accmulator, array[i], i, array)

        console.log("当前累计值:" + accmulator);
        console.log("当前索引值:" + i);

    }

    return accmulator
}

let testArr = [1, 2, 3, 4, 5]


let result = testArr.myReduce(
    (prev, next, index) => {
        prev += next;
        console.log(index)
        return prev;
    },
    10,
)
console.log(result)



参考资料

JavaScript 实现 reduce() 方法函数

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值