Array.prototype.filter()

Array.prototype.filter()

过滤,不会改变原数组

注意:它与map()方法不一样,map()是一次统一映射,不会改变数组长度。filter()是一次过滤,会挑选满足条件的,能改变数组长度

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
let a = words.filter(item => {
    return item.length > 5
});
console.log(a);  //[ 'exuberant', 'destruction', 'present' ]
  • 手动实现(必须要掌握,不要让它成为曾经会写的东西)
Array.prototype.filter = function (callbackfn, thisArg) {
    if (typeof callbackfn !=='function') throw new TypeError(callbackfn + 'must be a function')
    const arr = this
    const thisValue = thisArg || this
    const returnValue = []
    for (let i = 0; i < arr.length; i++) {
        if(callbackfn.call(thisValue, arr[i], i, arr)){
            returnValue.push(arr[i])
        }
    }
    return returnValue
};
let a = [1,2,3].filter(item => item > 1);
console.log(a);  //[ 2, 3 ]
posted @ 2022-06-13 18:38  朱在春  阅读(133)  评论(0编辑  收藏  举报