[TOC] #### 1. 前言 --- JavaScript 的 Array 對象方法太多了,短時間內記不住的,可以每天學幾個,日積月累,積少成多 ! ES6 中新增了很多實用的數組方法,`array.find()` 和 `array.findIndex` 就是其中兩個 `array.find()` 方法用于獲取數組中滿足指定條件的第一個元素的值 `array.findIndex()` 方法用于獲取數組中滿足指定條件的第一個元素的索引 ```javascript const array = [ { id: 1, name: 'tom' }, { id: 2, name: 'jerry' }, { id: 3, name: 'maria' }, ] ``` #### 2. array.find() --- 完整形式 ```javascript // item 數組元素 // index 數組索引 // array 當前元素所屬數組 // thisValue 參數1的函數體中的this指向,默認是Window對象 // 注意: 其中 index, array, thisValue 都是可選參數,大多數情況下都是只使用 item array.find(function(item, index, array) { }, thisValue) ``` 關于 `thisValue` 參數的用法 ```javascript array.find(function (item, index, array) { // 省略 thisValue 參數時, this 指向 Window 對象 console.log(this) }) const user = { name: 'liang' } array.find(function (item, index, array) { // 此時 this 指向 user 變量, // 特別注意: 當前函數必須為普通函數,不能用箭頭函數,懂的都懂 console.log(this) }, user) ``` 最常見的用法 ```javascript // 查找數組元素中 name 為 jerry 元素 // 找到返回該元素, 否則返回 undefined const item = array.find(item => item.name == 'jerry') ``` 也可以傳入一個函數名稱,效果是一樣的 ```javascript function jerryInfo(item) { return item.name == 'jerry'; } const item = array.find(jerryInfo) ``` #### 3. array.findIndex() --- array.findIndex() 參數同 array.find() 一致,都是用于查找滿足指定條件的數組中的第一個元素,區別是當能查找的到時, find 返回的是數組元素,findIndex 返回的是數組索引;當查找不到時,find 返回 undefined,findIndex 返回 -1 ```javascript const index = array.findIndex(item => item.name == 'jerry') console.log(index) // 1 const index = array.findIndex(item => item.name == 'cat') console.log(index) // -1 ```