JavaScript 中的数组搜索方法

JavaScript 提供了用于在数组中查找元素的内置方法。这些工具可以帮助您定位位置或检查某个值是否存在。

以下是您需要了解的主要方法:

  • indexOf() 查找特定元素的第一个索引。如果元素不存在,则返回 -1。 示例:
const fruits = ["Apple", "Banana", "Mango", "Banana"];
fruits.indexOf("Banana"); // 返回 1
  • lastIndexOf() 查找特定元素的最后一个索引。如果元素不存在,则返回 -1。 示例:
const fruits = ["Apple", "Banana", "Mango", "Banana"];
fruits.lastIndexOf("Banana"); // 返回 3
  • includes() 检查数组中是否存在某个元素。它返回 true 或 false。 示例:
const fruits = ["Apple", "Banana", "Mango"];
fruits.includes("Mango"); // 返回 true
fruits.includes("Orange"); // 返回 false
  • find() 返回满足条件的第一个元素。如果没有匹配项,则返回 undefined。 示例:
const numbers = [5, 12, 8, 20];
const result = numbers.find(num => num > 10); // 返回 12
  • findIndex() 返回满足条件的第一个元素的索引。如果没有匹配项,则返回 -1。 示例:
const numbers = [5, 12, 8, 20];
const index = numbers.findIndex(num => num > 10); // 返回 1
  • findLast() 返回满足条件的最后一个元素。它从数组末尾开始搜索。 示例:
const numbers = [5, 12, 8, 20];
const result = numbers.findLast(num => num > 10); // 返回 20
  • findLastIndex() 返回满足条件的最后一个元素的索引。 示例:
const numbers = [5, 12, 8, 20];
const index = numbers.findLastIndex(num => num > 10); // 返回 3

总结:

• indexOf() 获取第一个索引。 • lastIndexOf() 获取最后一个索引。 • includes() 检查是否存在。 • find() 获取第一个匹配的值。 • findIndex() 获取第一个匹配的索引。 • findLast() 获取最后一个匹配的值。 • findLastIndex() 获取最后一个匹配的索引。

来源:https://www.w3schools.com/js/js_array_search.asp

完整文章:https://dev.to/kamalesh_ar_6252544786997/array-search-methods-in-javascript-23mk