实现数组reduce和map方法

本文介绍如何手动实现JavaScript数组的reduce和map方法。reduce方法通过累积器将数组元素转化为单一值,而map则创建一个新数组,其结果是原数组每个元素调用提供的函数后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、reduce实现

reduce的用法:

 arr.reduce(function(pre,cur,index,arr){...return...}, initialValue);

 arr是原数组,可以传入两个参数,第一个参数是有返回值的函数,该函数可以有四个传参(前一个具有累加器性质的元素,当前元素,索引,原数组),第二个是初始值,可以选择性设置。

实现:

// arr.reduce(function(pre,cur,index,arr){...}, initialValue);
Array.prototype.myReduce = function(fn,initialValue){
    if(typeof fn !== "function"){
        throw new TypeError("argument[0] is not a function")
    }
    let initialArr = this;
    let arr = initialArr.concat();

    let index;
    if(arguments.length==2){
        arr.unshift(initialValue);
        index = 0;
    }else{
        index = 1;
    }

    let res;
    if(arr.length===1){
        res = arr[0];
    }
    while(arr.length>1){
        res = fn.call(null,arr[0],arr[1],index,arr)
        index++;
        arr.splice(0,2,res);
    }

    return res;
}

// 验证
var arr= [1,3,2,5,2,34];
var res = arr.myReduce(function(pre,cur,index,arr){
    console.log(index);  // 索引从1开始
    return pre+cur;
})
console.log(res);    // 47
var res1 = arr.myReduce(function(pre,cur,index,arr){
    console.log(index);  // 索引从0开始
    return pre+cur;
},3)
console.log(res1);   // 50

二、map实现

map的用法:

arr.map(function(item,index,arr){...return...},context)

 arr是原数组,可以传入两个参数,第一个参数是有返回值的函数,该函数可以有三个传参(当前元素,索引,原数组),第二个是上下文,可以选择性设置。

// arr.map(function(item,index,arr){...return...},context)
// 方法一:使用for循环实现
Array.prototype.myMap = function (fn, context){
    if(typeof fn !== 'function'){
        throw new TypeError("arguments[0] is not a function");
    }    
    let arr = this;
    let res = [];
    for(let i = 0; i < arr.length; i++){
        res.push(fn.call(context, arr[i], i, arr));
    }
    return res;
}

// 方法二:使用reduce函数实现
Array.prototype.newMap = function(fn,context){
    if(typeof fn !== 'function'){
        throw new TypeError("arguments[0] is not a function");
    }    
    let arr = this;
    let res = [];
    arr.reduce((pre, cur, index, arr) => {
        res.push(fn.call(context, cur, index, arr)); 
    }, 0)
    return res;
}

// 验证
let array = [1, 2, 3, 4, 5];
let myArr = array.myMap(function(item,index){
    return item * index;
})
console.log(myArr);
let newArr = array.newMap(function(item,index){
    return item * index;
})
console.log(newArr);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值