includes() 方法最简洁,返回布尔值,支持 nan 检查,但不兼容旧浏览器;2. indexof() 通过返回索引检查存在性,使用严格相等,不支持 nan;3. find()/findindex() 支持复杂条件和对象比较,但性能较低;4. 对于对象需自定义比较函数;5. 第三方库如 lodash 提供增强兼容性与功能。

在 JavaScript 中,检查数组是否包含特定元素有多种方法,选择哪种取决于你的具体需求和目标浏览器兼容性。最常用的方法包括
includes()、
indexOf()和
find()/
findIndex()。

includes()方法
includes()方法
includes()方法是 ES2016 (ES7) 引入的,它直接返回一个布尔值,表示数组是否包含给定的元素。这是最简洁和易读的方法。

const arr = [1, 2, 3, 4, 5]; console.log(arr.includes(3)); // true console.log(arr.includes(6)); // false
includes()方法接受两个参数:要搜索的元素和可选的起始搜索位置。
indexOf()方法
indexOf()方法返回数组中找到给定元素的第一个索引,如果不存在则返回 -1。 虽然它主要用于查找元素的索引,但也可以用来检查元素是否存在。

const arr = [1, 2, 3, 4, 5]; console.log(arr.indexOf(3) > -1); // true console.log(arr.indexOf(6) > -1); // false
indexOf()的一个缺点是它使用严格相等 (
===) 进行比较,这意味着它不会将字符串 "3" 与数字 3 视为相等。
find()和findIndex()方法
find()方法返回数组中满足提供的测试函数的第一个元素的值。
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。 如果没有找到满足条件的元素,
find()返回
undefined,
findIndex()返回 -1。
const arr = [1, 2, 3, 4, 5]; console.log(arr.find(element => element === 3) !== undefined); // true console.log(arr.findIndex(element => element === 6) > -1); // false
find()和
findIndex()的优点是它们允许你使用更复杂的条件来查找元素,例如,查找大于某个值的第一个元素。
性能考虑
对于大型数组,
includes()通常是最快的,因为它在找到匹配项后会立即停止搜索。
indexOf()的性能也相当不错。
find()和
findIndex()的性能可能略差,因为它们需要对数组中的每个元素执行测试函数。
兼容性
includes()方法在较旧的浏览器中可能不受支持。 如果你需要支持旧版本的浏览器,可以使用
indexOf()或
find()/
findIndex(),或者使用 Babel 等工具进行转译。
如何处理NaN值?
includes()可以正确处理
NaN值,而
indexOf()则不能。 这是因为
NaN === NaN的结果是
false。
const arr = [1, 2, NaN, 4, 5]; console.log(arr.includes(NaN)); // true console.log(arr.indexOf(NaN) > -1); // false
如何检查数组中是否存在对象?
如果数组包含对象,你需要使用
find()或
findIndex()方法,并提供一个自定义的比较函数。
const arr = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const obj = {id: 2, name: 'Bob'};
console.log(arr.find(item => item.id === obj.id && item.name === obj.name) !== undefined); // true使用第三方库
Lodash 和 Underscore.js 等第三方库提供了
_.includes()和
_.contains()方法,它们提供了额外的功能和兼容性。










