在 JavaScript 数组中搜索元素
Javascript 提供了一系列函数,您可以使用这些函数在数组中查找元素。让我们从最基本的开始。indexOf 函数遍历整个数组,并返回您搜索的元素的索引(如果找到),否则返回 -1。例如:
示例
let people = ["Harry", "Martha", "John", "Sam"];
console.log(people.indexOf("John"))
console.log(people.indexOf("Jim"))输出
这将给出以下输出:
2 -1
还有其他更复杂的函数,您可以使用它们使搜索更强大。让我们看看 find() 方法。find() 方法返回与您作为回调() 方法提供的条件匹配的第一个对象。例如:
示例
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