美文网首页
reduce实现map方法

reduce实现map方法

作者: isSunny | 来源:发表于2019-07-16 12:10 被阅读0次

reduce实现map方法,首先我们先来了解一下reduce和map:

1.reduce是一个累加方法,是对数组累积执行回调函数,返回最终计算结果。

array.reduce(function(total, currentValue, currentIndex, arr){
}, initialValue);

//total 必需。初始值, 或者计算结束后的返回值。
//currentValue  必需。当前元素
//currentIndex  可选。当前元素的索引
//arr   可选。当前元素所属的数组对象。
//initialValue可选。传递给函数的初始值

2.map是遍历数组的每一项,并执行回调函数的操作,返回一个对每一项进行操作后的新数组。

array.map(function(currentValue,index,arr), thisValue);
//currentValue  必须。当前元素的值
//index 可选。当前元素的索引值
//arr   可选。当前元素属于的数组对象
//thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。

说到map这里顺便把forEach也总结一下

3.forEach和map用法一样,也是是遍历数组的每一项,并执行回调函数的操作,不过forEachf返回值是undefined,不可以链式调用。

array.forEach(function(currentValue, index, arr), thisValue)

//currentValue  必需。当前元素
//index 可选。当前元素的索引值。
//arr   可选。当前元素所属的数组对象。
//thisValue 可选。传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值

这里说一下map和forEach的区别

1.forEach()返回值是undefined,不可以链式调用。
2.map()返回一个新数组,原数组不会改变。
3.没有办法终止或者跳出forEach()循环。

进入正题,知道了map和reduce的用法,下面我们来用reduce实现map方法。

Array.prototype.myMap = function(fn,thisValue){
    var res = [];
    thisValue = thisValue||[];
    this.reduce(function(pre,cur,index,arr){
            return res.push(fn.call(thisValue,cur,index,arr));
  },[]);
  return res;
}
var arr = [2,3,1,5];
arr.myMap(function(item,index,arr){
    console.log(item,index,arr);
})

附加一道恶心的面试题

["1", "2", "3"].map(parseInt); //结果 [1, NaN, NaN]

解释:parseInt()默认有两个参数,第二个参数是进制数。当parsrInt没有传入参数的时候,而map()中的回调函数时候,会给它传三个参数,第二个参数就是索引,所以返回NaN了。

相关文章

网友评论

      本文标题:reduce实现map方法

      本文链接:https://www.haomeiwen.com/subject/ihdmkctx.html