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

news/2024/7/19 15:22:51 标签: js, javascript, callback

文章目录

  • 定义和用法
  • 语法
  • 自己实现一个
    • 队列实现
    • 递归实现
    • 遍历数组实现
  • 参考资料




定义和用法

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

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




自己实现一个




队列实现

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

  • 不断地对数组的前两项“取出”,对其执行目标函数,计算得到的返回值
  • 把上述返回值“填回”数组首部,作为新的 队头
  • 重复上述过程,直到数组中每一项都访问了一次
  • 返回最终结果
javascript">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



递归实现

javascript">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)



遍历数组实现

javascript">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() 方法函数


http://www.niftyadmin.cn/n/555300.html

相关文章

网页布局方式:浮动和定位

1.文档流 文档流时整个页面的最底层&#xff0c;在页面中创建元素时默认情况下都在文档流。 元素在文档流里面的特点&#xff1a; 块元素&#xff1a;1&#xff09;块元素在文档流里会独占一行&#xff0c;块元素会自上向下垂直排列&#xff1b;2&#xff09;块元素在文档流中…

029_mac下nginx管理

一、 brew info nginx #查看nginx信息 nginx: stable 1.13.12 (bottled), HEAD Docroot is: /usr/local/var/wwwThe default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that nginx can run without sudo.nginx will load all files in /usr/local/…

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

文章目录语法简单示例实现参考资料语法 Map 作用是生成一个新数组&#xff0c;遍历原数组&#xff0c;将每个元素拿出来做一些变换然后 append到新的数组中。 [1, 2, 3].map((v) > v 1) // -> [2, 3, 4]Map 有三个参数&#xff0c;分别是当前索引元素&#xff0c;索引…

jqGrid基本使用及相关方法

1.初始化 定义一个标签容器&#xff0c;再在js代码中初始化&#xff1a; <table id"jqGrid"></table> $("#jqGrid").jqGrid({ url: data.json, editurl: clientArray, customEdit: true, data: [], autowidth: true, responsive: true,…

nginx 学习

Nginx简介&#xff1a; Nginx是linux系统下的高效网页服务器&#xff0c;搭配apache实现高性能服务。 Nginx&#xff08;Engine x&#xff09;&#xff0c;俄罗斯人开发的&#xff0c;开源的www服务软件 软件一共780k。 Nginx本身是一款静态&#xff08;html&#xff0c;js&…

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

文章目录语法简单示例动手实现参考资料语法 array.filter(function(currentValue,index,arr), thisValue)function(currentValue, index,arr) 必须。函数&#xff0c;数组中的每个元素都会执行这个函数 参数描述currentValue必须。当前元素的值index可选。当前元素的索引值a…

bootstrap modal加树状图

1.布局代码 <div id"myBedinfoModal" class"modal modal-dialog fade modal-lg" tabindex"-1" data-focus-on"input:first"><div class"modal-header"><div class"row"><div class"co…

dataTable实现会议预定

1.页面结构<table class"table table-striped table-bordered table-hover dataTable no-footer dt-responsive" id"data-table-actmReserve"><thead><tr role"row" class"heading"><th class""> 名…