在JavaScript开发过程中,判断数组是否包含某个特定元素是高频出现的操作,不同的方法在返回值、兼容性、判断逻辑上都有差异,开发者可以根据实际需求选择合适的方式。

使用includes方法检查
includes是ES6新增的数组方法,专门用于判断数组是否包含某个元素,返回值直接是布尔类型,使用起来非常直观。
该方法语法为arr.includes(searchElement[, fromIndex]),其中searchElement是要查找的元素,fromIndex是可选参数,表示从数组的哪个索引位置开始查找,默认从0开始。
// 基础使用示例
const arr = [1, 2, 3, 'hello', null, undefined, NaN];
console.log(arr.includes(2)); // 输出 true
console.log(arr.includes('hello')); // 输出 true
console.log(arr.includes(null)); // 输出 true
console.log(arr.includes(undefined)); // 输出 true
// includes可以正确判断NaN,这是它相比indexOf的优势
console.log(arr.includes(NaN)); // 输出 true
// 从索引2开始查找
console.log(arr.includes(3, 2)); // 输出 true
console.log(arr.includes(1, 2)); // 输出 false
使用indexOf方法检查
indexOf是ES5就存在的方法,它会返回指定元素在数组中第一次出现的索引,如果不存在则返回-1,通过判断返回值是否不等于-1可以确定元素是否存在。
语法为arr.indexOf(searchElement[, fromIndex]),参数含义和includes基本一致。
const arr = [1, 2, 3, 'hello', NaN];
console.log(arr.indexOf(2) !== -1); // 输出 true
console.log(arr.indexOf('hello') !== -1); // 输出 true
// indexOf无法正确判断NaN,因为NaN !== NaN
console.log(arr.indexOf(NaN) !== -1); // 输出 false
// 从索引1开始查找
console.log(arr.indexOf(2, 1) !== -1); // 输出 true
console.log(arr.indexOf(1, 1) !== -1); // 输出 false
使用find方法检查
find方法会返回数组中满足提供的测试函数的第一个元素的值,如果没有找到则返回undefined,适合需要自定义判断逻辑的场景,比如查找对象数组中某个属性符合条件的元素。
语法为arr.find(callback(element[, index[, array]])[, thisArg]),callback是执行每个元素的测试函数。
const userList = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' }
];
// 查找id为2的用户是否存在
const targetUser = userList.find(item => item.id === 2);
console.log(targetUser !== undefined); // 输出 true
// 查找name为赵六的用户
const noExistUser = userList.find(item => item.name === '赵六');
console.log(noExistUser !== undefined); // 输出 false
使用findIndex方法检查
findIndex和find类似,不过它返回的是满足条件的元素的索引,找不到则返回-1,同样支持自定义判断逻辑。
语法和find基本一致,只是返回值不同。
const userList = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' }
];
// 查找id为3的用户索引
const targetIndex = userList.findIndex(item => item.id === 3);
console.log(targetIndex !== -1); // 输出 true
// 查找name为王八的用户索引
const noExistIndex = userList.findIndex(item => item.name === '王八');
console.log(noExistIndex !== -1); // 输出 false
方法对比与选择建议
不同方法的适用场景可以参考下面的对比:
| 方法名 | 返回值 | 是否支持自定义逻辑 | 能否判断NaN | 兼容性 |
|---|---|---|---|---|
| includes | 布尔值 | 否 | 能 | ES6及以上 |
| indexOf | 索引/-1 | 否 | 不能 | ES5及以上 |
| find | 元素值/undefined | 能 | 能 | ES6及以上 |
| findIndex | 索引/-1 | 能 | 能 | ES6及以上 |
如果只是简单判断基本类型元素是否存在,优先使用includes,语义更清晰;如果需要兼容ES5环境,可以使用indexOf;如果是对象数组需要按自定义条件查找,选择find或findIndex即可。
JavaScript数组includesindexOffind修改时间:2026-07-19 19:03:23