js 实现filter

实现filter

/**
 * 实现filter
 * @param {*} cb cb : (predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]
 * @param {*} thisArg 
 */
Array.prototype._filter = function (cb, thisArg) {
    if (typeof cb !== 'function') {
        throw 'the parameter cb must be a function'
    }
    if (!Array.isArray(this)) {
        throw 'function _forEach must be used by Array'
    }

    const array = this
    const result = []
    for (let index = 0; index < array.length; index++) {
        const v = array[index];
        const match = cb.call(thisArg, v, index, array)
        match && result.push(v)
    }
    return result
}

// const filterArr = getRandomArrByRecursion(5)._filter(function(v,index,arr){
//     console.log(arguments,this);
//     return v < 100
// },{test:1})
// console.log('filter result: ', filterArr);
posted @ 2022-01-25 12:32  IslandZzzz  阅读(43)  评论(0编辑  收藏  举报