在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()andfindindex()函数将回调作为参数,而回调则将参数:element,index,array。这些功能仅给出该元素的首次出现。indexOf函数还采用了另一个参数fromIndex,以便您可以从该点开始继续搜索。例如,
示例
let people = ["Harry", "Martha", "John", "Sam", "Martha"];
console.log(people.indexOf("Martha"));
console.log(people.indexOf("Martha", 3))输出结果
这将给出输出-
1 4
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短