数组搜索和位置方法总结(indexOf()、lastIndexOf()、includes()、find()、findIndex())

1.严格相等(indexOf()、lastIndexOf()、includes())

这三个方法都接受两个参数(要查找的元素、可选的起始搜索位置)indexOf()、includes()从数组第一项往后搜索,lastIndexOf()从数组最后一项往前开始搜索

indexOf与lastIndexOf返回要查找的元素在数组中的位置,如果没有找到返回-1,incoudes返回布尔值,表示是否至少找到一个与指定元素匹配的项,在比较时会使用全等(===)比较

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


console.log(numbers.indexOf(4)); // 3,从数组第一项开始查找4,返回第一个4的位置索引3
console.log(numbers.lastIndexOf(4));  // 5,从数组最后一项开始查找,返回第一个查找到的4索引为5
console.log(numbers.includes(4));  // true,从数组第一项开始查找是否包含4


console.log(numbers.indexOf(4, 4));  // 5,从数组索引为4的地方开始搜索,返回第一个查找到的4的索引为5
console.log(numbers.lastIndexOf(4, 4));  // 3,从数组索引为4的地方向前搜索,查找到的第一个4的索引为3
console.log(numbers.includes(4, 7));  //  false,从数组索引为7的地方开始往后查找,没有4,所以返回false



let person = { name: "Nicholas" };
let people = [{ people: "Nicholas" }];
let morePeople = [person];
console.log(people.indexOf(person));  // -1,在比较对象的全等时,因为people和person看上去值是相等的,但是两者引用地址不一样,指向不同的对象,所以在判断全等时两者并不相等
console.log(morePeople.indexOf(person));  //  0,因为morePeople直接将person作为自己的第一个数组元素,所以morePeople[0]和person是同一个引用地址,指向同一个对象
console.log(people.includes(person));  //  false
console.log(morePeople.includes(person));  // true

2.断言函数(find()、findIndex()):每个索引都会调用这个函数,返回值决定了相应索引的元素是否被认为匹配。

断言函数接受三个参数(数组中当前搜索的元素、当前元素的索引、正在搜索的数组本身),返回真值,表示是否匹配。

find()、findIndex()都从数组的最小索引开始。find()返回第一个匹配的元素,findIndex()返回第一个匹配元素的索引,这两个方法都接受第二个可选的参数,用于指定断言函数内部this值。

const people = [
  {
      name: "Matt",
      age: 27
  },
  {
      name: "Nicholas",
      age: 29
  }
]

console.log(people.find((element, index, array) => element.age < 28)); // {name: "Matt", age: 27}

console.log(people.findIndex((element, index, array) => element.age < 28)); // 0

注:找到匹配项后,这两个方法都不再继续搜索

//找到匹配后,永远不会检查数组最后一个元素

const evens = [2, 4, 6];
evens.find((element, index, array) => {
  console.log(element);
  console.log(index);
  console.log(array);
  return element === 4
})

//  2
//  0
//  [2, 4, 6]
//  4
//  1
//  [2, 4, 6]
//找到匹配后,永远不会检查数组最后一个元素

const evens = [2, 4, 6];
evens.find((element, index, array) => {
  console.log(element);
  console.log(index);
  console.log(array);
  return element === 4
})

//  2
//  0
//  [2, 4, 6]
//  4
//  1
//  [2, 4, 6]

 

posted on 2024-04-12 11:46  zy89898976  阅读(9)  评论(0编辑  收藏  举报