1. 方法概述
1.1 includes的定义与基本行为
在 JavaScript 中,Array.prototype.includes 是用于判断数组中是否存在某个给定的值的实例方法。它的返回值是 布尔类型,当目标值存在于数组中时返回 true,否则返回 false。
核心行为是使用严格相等比较(===)来判断元素是否匹配,对于 NaN 的检测也不同于一般等于判断。
const arr = [1, 2, 3, NaN];
console.log(arr.includes(NaN)); // true
console.log(arr.includes(4)); // false1.2 includes与indexOf的区别
一个常见的疑问是 includes 与 indexOf 有何区别。includes 返回布尔值,而 indexOf 返回元素的位置索引,两者在语义上不同。
重要差异还在于 对 NaN 的处理:indexOf 使用严格相等进行逐一比较,但 NaN === NaN 为 false,因此 indexOf 无法检测 NaN;而 includes 可以检测到 NaN 是否在数组中。
const a = [1, 2, NaN];
console.log(a.indexOf(NaN)); // -1
console.log(a.includes(NaN)); // true2. 使用要点
2.1 fromIndex 的用法
fromIndex 参数用于指定从数组的哪个位置开始搜索,默认从 0 开始。负数值会从末尾向前计数,直到遇到匹配项。

重要的是要理解它如何影响搜索起点:如果 fromIndex 超出边界,返回值始终为 false。
const letters = ['x', 'y', 'z', 'a'];
console.log(letters.includes('a', -3)); // true
console.log(letters.includes('x', -1)); // false2.2 对引用类型与对象的注意事项
对于引用类型的元素,includes 使用的是严格相等比较,因此只有同一个对象引用才算匹配。
如需判断对象数组中某个属性值是否存在,通常需要结合 Array.prototype.some 或使用 映射成值数组再使用 includes。
const users = [{id: 1}, {id: 2}];
console.log(users.includes({id: 2})); // false
console.log(users.map(u => u.id).includes(2)); // true3. 兼容性与 polyfill
3.1 浏览器兼容性
包含 Includes 的方法在 ES2016(ECMAScript 7)及以上 的环境中原生支持较广,包括现代浏览器、Node.js 等。然而,IE11 及更早版本不支持。
在需要兼容的场景下,可以使用 polyfill,或通过条件分支降级实现相同的功能。
// 简单的 polyfill 实现
if (!Array.prototype.includes) {Object.defineProperty(Array.prototype, 'includes', {value: function(searchElement, fromIndex) {if (this == null) throw new TypeError('Cannot read property includes of null or undefined');const o = Object(this);const len = o.length >>> 0;if (len === 0) return false;const n = fromIndex | 0;let k = Math.max(n >= 0 ? n : len + n, 0);while (k < len) {if (o[k] === searchElement || (typeof o[k] === 'number' && typeof searchElement === 'number' && isNaN(o[k]) && isNaN(searchElement))) {return true;}k++;}return false;}});
}4. 场景案例与实战要点
4.1 判定数组中是否包含某个字符串
在表单校验、过滤数据等场景,使用 includes 能够更直观地表达“包含性”,且支持可选的起始位置参数。
如果要判断一个数组是否包含任意一个候选值,可以结合逻辑或:arr.includes('a') || arr.includes('b'),来覆盖多值匹配。
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('durian')); // false 

