在開發(fā)應用程序時,大多使用數組方法來獲取特定的值列表并獲取單個或多個匹配項。
在列出這兩種方法的區(qū)別之前,我們先來一一了解這些方法。
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() 方法創(chuàng)建一個包含所有通過測試函數的元素的新數組。如果沒有元素滿足測試函數,則返回一個空數組。
語法
- 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() 的區(qū)別與共點
共點
高階函數:這兩個函數都是高階函數。
區(qū)別
1、通過一個測試功能
find() 返回第一個元素。
filter() 返回一個包含所有通過測試函數的元素的新數組。
2、如果沒有值滿足測試函數
find() 返回未定義;
filter() 返回一個空數組;
原文鏈接:https://www.toutiao.com/a7046592218571850243/