• 欢迎光临~

js 实现filter

开发技术 开发技术 2022-01-25 105次浏览

实现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);
程序员灯塔
转载请注明原文链接:js 实现filter
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com