Javascript Array find() 方法

針對陣列中的每個元素,執行callback,回傳一個符合條件的元素的,否則回傳undefined

怎麼寫?

Array.prototype.find()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const employee = [
{name:'Amy',department:'AD', phone:1000},
{name:'Betty',department:'IT', phone:1200},
{name:'Mary',department:'PM', phone:1300},
{name:'Susan',department:'MIS', phone:1400},
{name:'Bill',department:'MIS', phone:1405},
]

// 從{array}找符合{condition}的{element}的值

// 1. 把callback寫成function來使用
// array.find(callback)
function callback(element) {
return element.phone === 1200
}
const value1 = employee.find(callback)
console.log(value1) // {name: "Betty", department: "IT", phone: 1200}

// 2. 把callback寫在括號內
// array.find(function(element){ return condition })
const value2 = employee.find(function(element){
return element.department === 'MIS'
})
console.log(value2) // {name: "Susan", department: "MIS", phone: 1400}

// 3. 把callback寫成箭頭函式
// array.find(element => condition)
const value3 = employee.find(element => element.name === 'Bill')
console.log(value3) // {name: "Bill", department: "MIS", phone: 1405}

參考

Array.prototype.find() - JavaScript | MDN