[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 ```