day3:js数组方法filter、shift、unshift、pop的逻辑实现

70 阅读1分钟

js数组方法filter的实现

    const arr = [1,2,null,3];
    Array.prototype._filter = function(cb) {
        if (typeof cb !== 'function') {
            throw new Error(`${cb} is not a Function`);
        }
        const that = [...this];
        const newArr = [];
        if(cb.constructor === Function) {
            if(cb === Boolean) {
                for(let i = 0, len = that.length; i<len; i++) {
                    const val = that[i];
                    if(val) {
                        newArr[newArr.length] = val;
                    }
                }
                return newArr;
            }
            return that;
        }
        for(let i = 0, len = that.length; i<len; i++) {
            const condition = cb(that[i], i, this);
            if (condition) {
                newArr[newArr.length] = that[i];
            }
        }
        return newArr;
    }
    const res = arr._filter(Boolean)
    console.log(res)
    // 输出结果:[1,2,3]const arr = [1,2,null,3];
    Array.prototype._filter = function(cb) {
        if (typeof cb !== 'function') {
            throw new Error(`${cb} is not a Function`);
        }
        const that = [...this];
        const newArr = [];
        if(cb.constructor === Function) {
            if(cb === Boolean) {
                for(let i = 0, len = that.length; i<len; i++) {
                    const val = that[i];
                    if(val) {
                        newArr[newArr.length] = val;
                    }
                }
                return newArr;
            }
            return that;
        }
        for(let i = 0, len = that.length; i<len; i++) {
            const condition = cb(that[i], i, this);
            if (condition) {
                newArr[newArr.length] = that[i];
            }
        }
        return newArr;
    }
    const res = arr._filter(Boolean)
    console.log(res)
    // 输出结果:[1,2,3]

js数组方法shift的实现

    Array.prototype._shift = function () {
        const that = [...this];
        for (let i = 0; i < that.length; i++) {
          this[i] = this[i + 1]
        }
        this.length --;
        return that[0]
    }
    const arr = [1, 2, 3];
    console.log(arr._shift(), arr);
    // 输出结果:1,[2,3]

js数组方法unshift的实现

Array.prototype._unshift = function (...arg) {
  const arr = [...arg, ...this];
  for (let i=0, len = arr.length; i < len; i++) {
    this[i] = arr[i];
  }
  return this.length
}
const arr = [1, 2, 3];
console.log(arr._unshift(11,22,33), arr);
// 输出结果:6,[11, 22, 33, 1, 2, 3]

js数组方法pop的实现

Array.prototype._pop = function () {
  const data = this[this.length - 1];
  this.length --;
  return data;
}
const arr = [1, 2, 3];
console.log(arr.pop(), arr);
// 输出结果:3,[1,2]