JavaScript中filter()和map()方法的區別


filter()和map()方法都會返回新數組,對原數組不會影響

filter()方法是根據一定的條件對原數組長度進行過濾返回一個新的數組,這個新數組改變了原數組的長度,不會改變原數組的內容。

map()方法是根據一定的條件對原數組內容進行處理返回一個新的數組,這個新數組不會改變原數組的長度,只改變原數組的內容。


filter()方法的使用:

對原數組的過濾,r適合得篩選后才能返回出去的數組

let a = [1, 2, 3, 4, 5, 6]
let newA = a.filter((x) => {
    if (x > 4) {
        return x
    }
})
console.log(a);     //(6) [1, 2, 3, 4, 5, 6]
console.log(newA);  //(2)[5,6]

如果改變原數組的內容,返回的原數組和新數組內容不會有任何變化,效果如下:

let a = [1, 2, 3, 4, 5, 6]
let newA = a.filter((x) => {
    return x + '個'
})
console.log(a);       //(6) [1, 2, 3, 4, 5, 6]
console.log(newA);    //(2)[5,6]

map()方法的使用:

將元素進行處理后返回到新數組。

let a = [1, 2, 3, 4, 5, 6]
let newA = a.map((x) => {
    return x + '個'
})
console.log(a);    //(6) [1, 2, 3, 4, 5, 6]
console.log(newA); //(6) ['1個', '2個', '3個', '4個', '5個', '6個']

如果改變原數組的長度,返回的新數組長度不會有任何變化,效果如下:

let a = [1, 2, 3, 4, 5, 6]
let newA = a.map((x) => {
    if (x > 4) {
        return x
    }
})
// console.log(a);  //(6) [1, 2, 3, 4, 5, 6]
console.log(newA);  //(6) [undefined, undefined, undefined, undefined, 5, 6]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM