javascript搜索算法怎么写_如何查找数组中的元素

JavaScript数组查找应按需选择方法:includes()判断存在性最简洁;indexOf()获取首次索引;find()/findIndex()支持条件匹配;for循环适合自定义逻辑

JavaScript 中查找数组元素,核心是根据需求选择合适算法:简单查找用内置方法,自定义逻辑用循环,大数据量或有序数组考虑二分搜索。

includes() 判断是否存在

最常用、最简洁的方式,适合只需要知道“有没有”的场景。它返回布尔值,不关心位置。

示例:

const arr = [3, 7, 12, 19, 25];
console.log(arr.includes(12)); // true
console.log(arr.includes(8));  // false

indexOf() 获取首次出现的索引

返回元素第一次出现的下标(从 0 开始),没找到返回 -1。适合需要位置信息的情况。

示例:

const arr = ['apple', 'banana', 'cherry', 'banana'];
console.log(arr.indexOf('banana')); // 1
console.log(arr.indexOf('grape'));  // -1

find()findIndex() 匹配条件

当查找逻辑不是简单相等(比如找大于 10 的第一个数、找 name 为 'Alice' 的对象),这两个方法更灵活。

  • find() 返回匹配的第一个元素本身
  • findIndex() 返回该元素的索引

示例:

const numbers = [4, 11, 18, 23, 30];
const firstBig = numbers.find(n => n > 15);     // 18
const firstBigIdx = numbers.findIndex(n => n > 15); // 2

const users = [{id:1,name:'Tom'}, {id:2,name:'Jerry'}]; const user = users.find(u => u.name === 'Jerry'); // {id:2, name:'Jerry'}

手动实现线性搜索(for 循环)

适合学习原理、或需精细控制流程(如记录所有匹配位置、提前终止、处理特殊边界)。

示例(找所有匹配索引):

function findAllIndices(arr, target) {
  const indices = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) indices.push(i);
  }
  return indices;
}
console.log(findAllIndices([1, 2, 2, 3, 2], 2)); // [1, 2, 4]

有序数组用二分搜索(提升效率)

仅适用于已排序数组。时间复杂度 O(log n),比线性搜索快得多。JavaScript 没内置,需手写。

示例(升序数组中查找):

function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}
console.log(binarySearch([2, 5, 8, 12, 16], 8)); // 2

不复杂但容易忽略