首页 > 编程语言 > 详细

手写ES6数组方法

时间:2020-05-06 22:27:35      阅读:58      评论:0      收藏:0      [点我收藏+]
Array.prototype.customMap = function (fn) {
  let newArr = [];
  for (let i = 0, l = this.length; i < l; i++) {
    newArr.push(fn(this[i]), i, this)
  }
  return newArr;
}
Array.prototype.customFilter = function (fn) {
  let newArr = [];
  for (let i = 0, l = this.length; i < l; i++) {
    if (fn(this[i])) {
      newArr.push(fn(this[i], i, this))
    }
  }
  return newArr;
}
Array.prototype.customSort = function (fn) {
  let t;
  fn = fn || function (a, b) {
    return a - b;
  }
  for (let i = 0, l = this.length; i < l; i++) {
    for (let j = i; j < l; j++) {
      if (fn(this[i], this[j]) > 0) {
        t = this[i];
        this[i] = this[j];
        this[j] = t;
      }
    }
  }
}
Array.prototype.customReduce = function (fn) {
  if (!this.length) {
    throw ‘no value‘
  }
  let prev = 0;
  for (let i = 0, l = this.length; i < l; i++) {
    prev = fn(prev, this[i], i, this);
  }
  return prev;
}

手写ES6数组方法

原文:https://www.cnblogs.com/superlizhao/p/12837900.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!