在 Javascript 数组中搜索元素

javascriptweb developmentfront end technology

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

相关文章


有用资源