JS基础之实现数组reduce方法

实现数组reduce方法

Array.prototype.myReduce = function (callback, init) {
  if (!Array.isArray(this)) throw new TypeError('my reduce only use in Array');
  if (typeof callback !== 'function') throw new TypeError('callback is not a Function');
  let result = this[0];
  let _this = [...this];
  if (init !== undefined) {
    result = init;
    _this = [init, ...this];
  }
  for (let i = 1; i < _this.length; i++) {
    result = callback(result, _this[i]);
  }
  return result;
};

你可能感兴趣的:(前端笔试,javascript,前端,开发语言)