用法簡介:
find()方法會返回滿足條件的第一個元素,如果沒有,則返回undefined
var arr = [1, 2, 3, 4, 5];
var above5 = arr.find(ele => ele > 5);
var below5 = arr.find(ele => ele < 5);
console.log(above5); // undefined
console.log(below5); // 1
開發(fā)背景:
實際開發(fā)中,經(jīng)常會要求實現(xiàn)搜索功能。比如,根據(jù)姓名/用戶id等可以標明用戶唯一身份的字段值,搜索出對應(yīng)的某一條用戶數(shù)據(jù)等等。
實現(xiàn)思路:
通常的實現(xiàn)思路是,先遍歷所有數(shù)據(jù),然后根據(jù)用戶輸入的唯一的字段值,找出用戶想要的那一條數(shù)據(jù),然后展示在頁面上。
代碼示例:
假設(shè)根據(jù)用戶名查找某一個用戶
let input_user_name = "tom" // 假設(shè)用戶在輸入框中輸入的用戶名
const users = [ // 假設(shè)后端返回的所有數(shù)據(jù)
{ id: 123, name: "dave", age: 23 },
{ id: 456, name: "chris", age: 22 },
{ id: 789, name: "bob", age: 21 },
{ id: 101, name: "tom", age: 25 },
{ id: 102, name: "tim", age: 20 }
]
我之前的寫法是:
let userSearched
users.forEach(user => {
if (user.name === input_user_name) {
userSearched = user
}
})
在了解了ES6中的Array.prototype.find()之后,我重寫了之前的代碼:
let userSearched = users.find(user => user.name === input_user_name)
只需一行代碼搞定!