搜索和位置方法
ECMAScript 提供两类搜索数组的方法:按严格相等搜索和按断言函数搜索。
按严格相等搜索
ECMAScript 提供了 3 个严格相等的搜索方法:indexOf()
、lastIndexOf()
和includes()
。其中,前两个方法在所有版本中都可用,而第三个方法是ECMAScript 7
新增的。这些方法都接收两个参数:要查找的元素
和一个可选的起始搜索位置
。indexOf()
和includes()
方法从数组前头(第一项)开始向后搜索,而lastIndexOf()
从数组末尾(最后一项)开始向前搜索。indexOf()
和lastIndexOf()
都返回要查找的元素在数组中的位置,如果没找到则返回-1。includes()
返回布尔值,表示是否至少找到一个与指定元素匹配的项。在比较第一个参数跟数组每一项时,会使用全等(===
)比较,也就是说两项必须严格相等。
方法 | 参数一 | 参数二(可选) | 搜索方向 | 返回值 |
---|---|---|---|---|
indexOf | 要查找的元素 | 起始搜索位置 | 从前向后 | 元素下标(或-1) |
lastIndexOf | 要查找的元素 | 起始搜索位置 | 从后向前 | 元素下标(或-1) |
includes | 要查找的元素 | 起始搜索位置 | 从前向后 | Boolean 值 |
试一试
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]
numbers.indexOf(4)
numbers.lastIndexOf(4)
numbers.includes(4)
numbers.indexOf(4, 4)
numbers.lastIndexOf(4, 4)
numbers.includes(4, 7)
let person = { name: 'Nicholas' }let people = [{ name: 'Nicholas' }]let morePeople = [person]
people.indexOf(person)
morePeople.indexOf(person)
people.includes(person)
morePeople.includes(person)
示例代码
js
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]
console.log(numbers.indexOf(4)) // 3
console.log(numbers.lastIndexOf(4)) // 5
console.log(numbers.includes(4)) // true
console.log(numbers.indexOf(4, 4)) // 5
console.log(numbers.lastIndexOf(4, 4)) // 3
console.log(numbers.includes(4, 7)) // false
let person = { name: 'Song' }
let people = [{ name: 'Song' }]
let morePeople = [person]
console.log(people.indexOf(person)) // -1
console.log(morePeople.indexOf(person)) // 0
console.log(people.includes(person)) // false
console.log(morePeople.includes(person)) // true
按断言函数搜索
ECMAScript 也允许按照定义的断言函数搜索数组,每个索引都会调用这个函数。断言函数的返回值决定了相应索引的元素是否被认为匹配。
断言函数接收 3 个参数:元素、索引和数组本身。其中元素是数组中当前搜索的元素,索引是当前元素的索引,而数组就是正在搜索的数组。断言函数返回真值,表示是否匹配。find()
和findIndex()
方法使用了断言函数。这两个方法都从数组的最小索引开始。find()
返回第一个匹配的元素,findIndex()
返回第一个匹配元素的索引。这两个方法也都接收第二个可选的参数,用于指定断言函数内部 this 的值。
示例代码
js
const people = [
{
name: 'song',
age: 18,
},
{
name: 'xu',
age: 20,
},
]
console.log(people.find((element, index, array) => element.age < 19)) // {name: "song", age: 18}
console.log(people.findIndex((element, index, array) => element.age < 19)) // 0
找到匹配项后,这两个方法都不再继续搜索。
示例代码
js
const evens = [2, 4, 6]
// 找到匹配后,永远不会检查数组的最后一个元素
evens.find((element, index, array) => {
console.log(element)
console.log(index)
console.log(array)
return element === 4
})
// 2
// 0
// [2, 4, 6]
// 4
// 1
// [2, 4, 6]