跳到正文

手写练习/数组

GitHub

手写 Array.prototype.filter

中等原型链

代码实现

JavaScript18 行
Array.prototype.myFilter = function(callback){
    if(typeof callback !== 'function'){
        throw new TypeError(callback + ' is not a function')
    }

    const res = []
    const len = this.length

    for(let i = 0; i < len; i++){
        callback(this[i], i , this) && res.push(this[i])
    }

    return res
}

const arr = [1,2,3,4]
const res = arr.myFilter(item => item > 2)
console.log(res) //[3, 4]