fedono / fe-questions

1 stars 0 forks source link

实现JS原生 map/reduce #44

Open fedono opened 1 year ago

fedono commented 1 year ago
Array.prototype.myReduce = function (callback, initialValue) {
    const argsLength = arguments.length

    if (argsLength === 1 && this.length === 0) {
      throw new Error()
    }

    let index = argsLength === 1 ? 1 : 0
    let resultValue = argsLength === 1 ? this[0] : initialValue

    for (let i = index; i < this.length; i += 1) {
      resultValue = callback(resultValue, this[i], i, this)
    }

    return resultValue
  }
fedono commented 1 year ago

实现 map

这里的重点是,你自定义之后的传参,以及如何返回

  1. 第一个参数是

Array.prototype.myMap = function (callback, thisObj) {
  const result = [];
  this.forEach((...args) => {
    const index = args[1];
    result[index] = callback.apply(thisObj, args);
  });
  return result;
};

const arr = [1, 2, 3];
const res = arr.myMap((curr, id, array) => {
  console.log(curr, id, array);
  return curr + 1;
});

console.log(res);

通过 es 标准实现


// Based on ECMAScript spec https://262.ecma-international.org/6.0/#sec-array.prototype.map

Array.prototype.myMap = function(callback, ...args) {
  let thisObject = Object(this)

  if(!thisObject) {
    throw new TypeError("this is null")
  }

  if(typeof callback !== "function"){
    throw new TypeError(callback + " is not a function")
  }

  let length = thisObject.length, mapped = new Array(length)
  let thisParameter = args.length ? args[0] : undefined

  for(let i = 0; i < length; i++){
    // Handle sparse array
    if(i in thisObject){
      // support this binding
      mapped[i] = callback.call(thisParameter, thisObject[i], i, thisObject)
    }
  }
  return mapped
}

来源 implement-Array-prototype-map