An array of reduce
let arr = [1, 2, 3, 4, 5]; Array.prototype.myReduce = function (fn, initVal) { for (let i = 0; i < this.length; i++) { initVal = fn(initVal, this[i]); } return initVal; }; let a = arr.myReduce(function (pre, el) { return pre + el; }, 0); console.log(a); / / 15Copy the code
An array of foreach
let arr = [1, 2, 3, 4, 5]; Array.prototype.myForeach = function (fn) { for (let i = 0; i < this.length; i++) { fn(this[i]); }}; let a = arr.myForeach(function (el) { console.log(el); // 1 2 3 4 5});Copy the code
An array of map
let arr = [1, 2, 3, 4, 5];

Array.prototype.myMap = function (fn) {
  let tempArr = [];
  for (let i = 0; i < this.length; i++) {
    tempArr.push(fn(this[i]));
  }
  return tempArr;
};

let a = arr.myMap(function (el) {
  return (el *= 2);
});

console.log(a); // 2 4 6 8 10

Copy the code
An array of the filter
let arr = [1, 2, 3, 4, 5]; Array.prototype.myFilter = function (fn) { let tempArr = []; for (let i = 0; i < this.length; i++) { fn(this[i]) && tempArr.push(this[i]); } return tempArr; }; let a = arr.myFilter(function (el) { return el > 2; }); console.log(a); / / 3, 4, 5Copy the code
An array of some
let arr = [1, 2, 3, 4, 5];
Array.prototype.mySome = function (fn) {
  let res = false;
  for (let i = 0; i < this.length; i++) {
    if (fn(this[i])) {
      res = true;
      break;
    }
  }
  return res;
};

let a = arr.mySome(function (el) {
  return el > 2;
});

console.log(a); // true

Copy the code
An array of every
let arr = [1, 2, 3, 4, 5]; Array.prototype.mySome = function (fn) { for (let i = 0; i < this.length; i++) { if (fn(this[i])) { return true; } return false; }}; let a = arr.mySome(function (el) { return el > 0; }); console.log(a); //trueCopy the code