zoukankan      html  css  js  c++  java
  • 手写ES6数组方法

    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;
    }
    Array.prototype.customFrom = function (obj) {
      return [].slice.call(obj)
    };
    
  • 相关阅读:
    浮点数
    2020.07.13
    2020.07.07
    2020.07.06
    剑指offer(三)
    剑指offer(二)
    剑指offer
    堆排序
    归并排序
    希尔排序
  • 原文地址:https://www.cnblogs.com/superlizhao/p/12837900.html
Copyright © 2011-2022 走看看