在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
热门推荐
4 十月简短祝福语
10 简短大气的狗年祝福语
11 药店祝福语简短10字
12 新娘上头祝福语大全简短
13 祝福语大全简短赞美同学
14 虎年公司祝福语简短的
15 足球队祝福语简短
16 18岁祝福语搞笑简短
17 红颜生日祝福语简短独特
18 婚礼祝福语简短情话短句