JavaScript中find()和 filter()方法的區別小結


前言

JavaScript 在 ES6 上有很多數組方法,每種方法都有獨特的用途和好處。

在開發應用程序時,大多使用數組方法來獲取特定的值列表並獲取單個或多個匹配項。

在列出這兩種方法的區別之前,我們先來一一了解這些方法。

JavaScript find() 方法

ES6 find() 方法返回通過測試函數的第一個元素的值。如果沒有值滿足測試函數,則返回 undefined。

語法

以下語法中使用的箭頭函數。

find((element) => { /* ... */ } )
find((element, index) => { /* ... */ } )
find((element, index, array) => { /* ... */ } )

我們有一個包含名稱 age 和 id 屬性的用戶對象列表,如下所示:

let users = [{
    id:1,
    name: 'John',
    age: 22
}, {
    id:2,
    name: 'Tom',
    age: 22
}, {
    id:3,
    name: 'Balaji',
    age: 24
}];

以下代碼使用 find() 方法查找年齡大於 23 的第一個用戶。

console.log(users.find(user => user.age > 23));
//console
//{ id: 3, name: 'Balaji', age:24}

現在我們要找到第一個年齡為 22 的用戶

console.log(users.find(user => user.age === 22));
//console
//{ id: 1, name: 'John', age:22}

假設沒有找到匹配意味着它返回 undefined

console.log(users.find(user => user.age === 25));
//console
//undefined

JavaScript filter() 方法

filter() 方法創建一個包含所有通過測試函數的元素的新數組。如果沒有元素滿足測試函數,則返回一個空數組。

語法

filter((element) => { /* ... */ } )
filter((element, index) => { /* ... */ } )
filter((element, index, array) => { /* ... */ } )

我們將使用相同的用戶數組和測試函數作為過濾器示例。

以下代碼使用 filter() 方法查找年齡大於 23 的第一個用戶。

console.log(users.filter(user => user.age > 23));
//console
現在我們要過濾年齡為 22 歲的用戶//[{ id: 3, name: 'Balaji', age:24}]

現在我們要過濾年齡為 22 歲的用戶

console.log(users.filter(user => user.age === 22));
//console
//[{ id: 1, name: 'John', age:22},{ id: 2, name: 'Tom', age:22}]

假設沒有找到匹配意味着它返回一個空數組

console.log(users.filter(user => user.age === 25));
//console
//[]

find() 和 filter() 的區別與共點

共點

高階函數:這兩個函數都是高階函數。

 find 和 filter 都不改變原數組

區別

1、通過一個測試功能

find() 返回第一個元素。

filter() 返回一個包含所有通過測試函數的元素的新數組。

2、如果沒有值滿足測試函數

find() 返回未定義;

filter() 返回一個空數組。


免責聲明!

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



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