数组API:map、filter、reduce实现

基础

一、数组的 map、filter、reduce 是典型的高阶函数,就是接收函数做为参数的函数;
二、这三个函数都是在Array的原型上;数组

map

map() 方法建立一个新数组,其结果是该数组中的每一个元素是调用一次提供的函数后的返回值;
arr.map(function callback(currentValue[, index[, array]]),callback 提供了三个参数,当前元素、下标、源数组。ide

Array.prototype.myMap = function (fn) {  const that = this;  const result = [];  
  const length = that.length;  for (let i = 0; i < length; i++) {
    result.push(fn.call(that, that[i], i, that))
  }  return result
}复制代码

filter

filter() 方法建立一个新数组, 其包含经过所提供函数实现的测试的全部元素;
arr.filter(callback(element[, index[, array]])[, thisArg]),callback 被调用时传入三个参数:元素的值、元素的索引、被遍历的数组自己。函数

Array.prototype.myFilter = function (fn) {  const that = this;  const result = [];  
  const length = that.length;  for (let i = 0; i < length; i++) {const boolean = fn.call(that, that[i], i, that)
    boolean && result.push(that[i])
  }  return result
}复制代码

reduce

reduce() 方法对数组中的每一个元素执行一个reducer函数,将其结果汇总为单个返回值;
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue]);
callback函数被调用时传入三四个参数:累计器、当前值、当前索引、源数组;
initialValue 是第一次调用 callback函数时的第一个参数的值。 若是没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。测试

注意点:若是没有提供 initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。若是提供 initialValue,从索引0开始。this

Array.prototype.myReduce = function (fn, initialValue) {  const that = this;  if (that.length === 0) return;  let result = initialValue || arr[0];  let startIndex = initialValue ? 0 : 1;  
  const length = that.length;  for (let i = startIndex; i < length; i++) {
    result = fn.call(that, result, that[i], i, that);
  }  return result;
}复制代码
相关文章
相关标签/搜索