数组基本操作的背后

90 阅读1分钟
数组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);  //15

数组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
});

数组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

数组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 5

数组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

数组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);  //true