在 JavaScript 中,如果你想检查某个元素在数组中的索引值,可以使用以下两种最常用的方法:


✅ 方法一:indexOf()

📌 用法:

array.indexOf(searchElement, fromIndex)
  • searchElement:要查找的元素
  • fromIndex(可选):从该索引开始搜索,默认是 0
  • 返回值:元素的索引,如果不存在返回 -1

✅ 示例:

const fruits = ['apple', 'banana', 'cherry'];
const index = fruits.indexOf('banana'); // 1
const notFound = fruits.indexOf('grape'); // -1

✅ 方法二:findIndex()

📌 用法:

array.findIndex(callback(element, index, array), thisArg)
  • 用于按条件查找元素的索引
  • 常用于对象数组、复杂结构

✅ 示例:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

const index = users.findIndex(user => user.name === 'Bob'); // 1

✅ 快速判断是否存在的写法(可结合 includes()

const arr = ['a', 'b', 'c'];
if (arr.includes('b')) {
  const index = arr.indexOf('b');
  console.log(`'b' 在索引位置:${index}`);
}

🚫 注意:

  • indexOf 只能查找基础类型(字符串、数字等),对象比较时无法按值查找;
  • findIndex 更适合用于对象数组或更复杂的匹配条件;
  • indexOf 使用的是严格相等(===)判断。

好的!下面我帮你整理一个更完整的关于 JavaScript 中查找元素索引的实用技巧与示例合集,内容涵盖基础用法、对象数组查找、以及性能和注意点,适合做笔记、教程或面试复习。


JavaScript 查找数组中元素索引的实用技巧与示例


1. 基础方法:indexOf

  • 只能用于查找基本类型(字符串、数字、布尔值等)
  • 使用严格相等(===)判断
  • 找不到返回 -1
const arr = ['apple', 'banana', 'cherry'];

console.log(arr.indexOf('banana')); // 输出:1
console.log(arr.indexOf('grape'));  // 输出:-1

2. 查找对象数组中的索引:findIndex

  • 用于复杂条件查找
  • 传入回调函数,返回符合条件的第一个元素索引
  • 找不到返回 -1
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

const index = users.findIndex(user => user.id === 2);
console.log(index); // 输出:1

3. 快速判断元素是否存在且获取索引

结合 includes 与 indexOf,避免无用查找:

const arr = ['a', 'b', 'c'];

if (arr.includes('b')) {
  const idx = arr.indexOf('b');
  console.log(`元素 b 的索引是:${idx}`);
} else {
  console.log('元素 b 不存在');
}

4. 查找最后一个匹配元素的索引:lastIndexOf

  • 从数组末尾向前查找
  • 适用于可能有重复元素的数组
const arr = [1, 2, 3, 2, 1];

console.log(arr.lastIndexOf(2)); // 输出:3

5. 注意点与性能建议

方法支持类型返回值适用场景
indexOf基本类型第一个匹配元素的索引简单查找元素
lastIndexOf基本类型最后一个匹配元素的索引查找重复元素中的最后一个
findIndex任意类型及复杂条件第一个符合条件元素索引查找对象或复杂条件
  • indexOf 和 lastIndexOf 使用严格相等,不能查找对象内容
  • findIndex 性能相对略低,但功能更强大
  • 对于非常大的数组,建议合理选择查找方式,避免多次遍历

6. 结合实战:封装通用查找函数

/**
 * 查找元素索引,支持基本类型和对象条件查找
 * @param {Array} arr 数组
 * @param {any|function} target 目标元素或条件函数
 * @returns {number} 索引,找不到返回 -1
 */
function findIndexCustom(arr, target) {
  if (typeof target === 'function') {
    return arr.findIndex(target);
  }
  return arr.indexOf(target);
}

// 用法示例
const fruits = ['apple', 'banana', 'cherry'];
console.log(findIndexCustom(fruits, 'banana')); // 1

const users = [{id: 1}, {id: 2}];
console.log(findIndexCustom(users, u => u.id === 2)); // 1

如果你需要,我可以帮你:

  • 生成带注释的完整代码示例文件(JS/TS)
  • 做成面试题速查表或答题卡
  • 撰写深入的数组查找技巧专题教程
  • 制作微信公众号图文排版稿