在 JavaScript 数组中搜索元素
Javascript 提供了一组函数,可用于查找数组中的元素。让我们从最基本的函数开始。indexOf 函数遍历整个数组,并返回搜索元素的索引(如果找到),否则返回 -1。例如:
示例
let people = ["Harry", "Martha", "John", "Sam"];
console.log(people.indexOf("John"))
console.log(people.indexOf("Jim"))输出
这将给出以下输出:
2 -1
还有其他更复杂的函数可以用来增强搜索功能。让我们看看 find() 方法。find() 方法返回与您作为 callback() 方法提供的条件匹配的第一个对象。例如:
示例
let people = [{
name: 'Agnes',
age: 25
}, {
name: 'Richard',
age: 21
}, {
name: 'Zoe',
age: 35
}];
let personNameStartsWithR = people.find(person => person.name[0] === 'R');
console.log(personNameStartsWithR)输出
这将给出以下输出:
{ name: 'Richard', age: 21 }但是上面的结果给我们一个对象。我们可以使用 findIndex 函数找到这个对象的索引。例如:
示例
let people = [{
name: 'Agnes',
age: 25
}, {
name: 'Richard',
age: 21
}, {
name: 'Zoe',
age: 35
}];
let personNameStartsWithR = people.findIndex(person => person.name[0] === 'R');
console.log(personNameStartsWithR)输出
这将给出以下输出:
1
请注意,find() 和 findIndex() 函数将回调作为参数,回调函数接受参数:元素、索引、数组。这些函数只返回元素的第一次出现。indexOf 函数还接受另一个参数 fromIndex,以便您可以从该点继续搜索。例如:
示例
let people = ["Harry", "Martha", "John", "Sam", "Martha"];
console.log(people.indexOf("Martha"));
console.log(people.indexOf("Martha", 3))输出
这将给出以下输出:
1 4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP