手动实现 JS 操作对象、数组的一些 方法 call、apply、bind、find、map、forEach、filter

384 阅读1分钟
  • 1、手动实现 call 方法
  • 2、手动实现 apply 方法
  • 3、手动实现 bind 方法
  • 4、手动实现 find 方法
  • 5、手动实现 map 方法
  • 6、手动实现 forEach 方法
  • 7、手动实现 filter 方法

1、手动实现 call 方法

Function.prototype.mycall = function(obj) {
    const args = Array.from(arguments).slice(1)
    obj.fn = this
    obj.fn(...args)
    delete obj.fn
}

// function fn(params) {
//    console.log(this.name, params)
// }

// const obj = {name: 'ceshi'}
// fn.mycall(obj, 1111) //ceshi 1111

2、手动实现 apply 方法

// 手动实现apply
Function.prototype.myapply = function(obj) {
    const args = Array.from(arguments).slice(1)
    obj.fn = this
    args.length && obj.fn(...args[0]) || obj.fn()
    delete obj.fn
}


// function fn(params) {
//     console.log(this.name, params)
// }

// const obj = {name: 'ceshi'}
// fn.myapply(obj, 1111) //ceshi 1111

3、手动实现 bind 方法

Function.prototype.mybind = function (obj) {
    const args = Array.prototype.slice.call(arguments, 1);
    const fn = this;
    return function () {
        const params = Array.prototype.slice.call(arguments);
        fn.apply(obj, args.concat(params));
    };
};

4、手动实现 find 方法

Array.prototype.myfind = function(fn) {
    for (let i = 0; i < this.length; i++) {
        if (fn(this[i], i, this)) {
            return this[i]
        }
    }
}

5、手动实现 map 方法

Array.prototype.mymap = function(fn) {
  const arr = []
    for (let i = 0; i < this.length; i++) {
        arr.push(fn(this[i], i, this))
    }
    return arr
}

6、手动实现 forEach 方法

Array.prototype.myforEach = function(fn) {
    for (let i = 0; i < this.length; i++) {
        fn(this[i], i, this)
    }
}

7、手动实现 filter 方法

Array.prototype.myfilter = function(fn) {
    let arr = []
    for (let i = 0; i < this.length; i++) {
        if (fn(this[i],i,this)) {
            arr.push(this[i])
        }
    }
    return arr
}