map和filter的区别

527 阅读1分钟

map

  • 对数组中的数据进行处理,修改等操作,然后返回一个新的数组
let arr = [1, 2, 3, 4, 5]
let arr1 = []
let a = arr.map((item, index) => {
    if (item % 2 === 0) {
        return item
    }
})
console.log(a) // [ undefined, 2, undefined, 4, undefined ]

filter

  • 对数组中的内容进行过滤处理,符合条件的留下返回一个新的数组
let arr = [1, 2, 3, 4, 5]
let arr2 = []
let b = arr.filter((item, index) => {
    if (item % 2 === 0) {
        return item

    }
})
console.log(b); // [ 2, 4 ]

区别

  • map是对原数组进行操作,如果处理结果不符合返回undefined放回到数组中, 而filter是对数组进行过滤,留下符合条件的数据返回到新数组,不符合的全部过滤出去