Array.prototype.includes是JavaScript数组的原型方法,主要作用是判断当前数组是否包含给定的值,返回布尔值结果,是ES6规范中新增的数组操作方法,相比传统的查找方式更加直观易用。

includes方法的基本语法
includes方法的语法格式如下:
arr.includes(valueToFind[, fromIndex])
其中各个参数的含义为:
- valueToFind:必填参数,需要查找的目标值。
- fromIndex:可选参数,开始查找的索引位置,默认值为0。如果fromIndex大于等于数组长度,会直接返回false;如果fromIndex为负数,则会从数组末尾向前计算起始位置,比如fromIndex为-1表示从倒数第一个元素开始查找。
方法的返回值是布尔类型,如果数组中包含目标值则返回true,否则返回false。
includes方法的基本使用示例
下面是一些常见的使用场景示例:
// 基础查找示例 const arr = [1, 2, 3, 4, 5]; console.log(arr.includes(3)); // 输出 true console.log(arr.includes(6)); // 输出 false // 使用fromIndex参数 console.log(arr.includes(2, 2)); // 从索引2开始查找2,输出 false console.log(arr.includes(2, 1)); // 从索引1开始查找2,输出 true // fromIndex为负数的情况 console.log(arr.includes(3, -2)); // 从倒数第二个元素开始查找3,输出 false console.log(arr.includes(4, -2)); // 从倒数第二个元素开始查找4,输出 true
includes与indexOf的区别
在includes方法出现之前,开发者通常使用indexOf方法来判断数组是否包含某个值,两者的区别主要体现在以下方面:
| 对比项 | includes方法 | indexOf方法 |
|---|---|---|
| 返回值类型 | 布尔值,直接返回是否包含 | 数字,返回匹配到的第一个索引,没有则返回-1 |
| NaN的处理 | 可以正确判断NaN是否存在 | 无法正确判断NaN,indexOf(NaN)始终返回-1 |
| 判断逻辑 | 使用SameValueZero算法比较,更宽松 | 使用严格相等比较,对NaN等特殊值不友好 |
下面是两者的对比示例:
const testArr = [1, NaN, 3];
console.log(testArr.includes(NaN)); // 输出 true
console.log(testArr.indexOf(NaN)); // 输出 -1
// 判断是否存在元素时的写法差异
// includes写法更直观
if (testArr.includes(1)) {
console.log('数组包含1');
}
// indexOf写法需要额外判断
if (testArr.indexOf(1) !== -1) {
console.log('数组包含1');
}
includes方法的特殊场景处理
处理稀疏数组
如果数组中存在空位,includes方法会将空位视为undefined进行查找:
const sparseArr = [1, , 3]; console.log(sparseArr.includes(undefined)); // 输出 true console.log(sparseArr.includes(2)); // 输出 false
处理对象引用
includes方法判断对象时,比较的是引用地址,而不是对象的内容:
const obj = { name: 'test' };
const arrWithObj = [obj];
console.log(arrWithObj.includes(obj)); // 输出 true
console.log(arrWithObj.includes({ name: 'test' })); // 输出 false,对象引用不同
实际开发中的使用建议
在实际开发中,如果只是需要判断数组是否包含某个值,优先使用includes方法,代码可读性更高。如果还需要获取目标值的索引位置,再使用indexOf方法。另外需要注意includes方法是ES6新增的,如果需要兼容IE等不支持ES6的环境,可以通过添加polyfill的方式实现兼容,polyfill示例代码如下:
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(valueToFind, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
const o = Object(this);
const len = o.length >>> 0;
if (len === 0) {
return false;
}
const n = fromIndex | 0;
const k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (Number.isNaN(x) && Number.isNaN(y));
}
while (k < len) {
if (sameValueZero(o[k], valueToFind)) {
return true;
}
k++;
}
return false;
}
});
}
Array.prototype.includesJavaScript数组方法数组查找ES6新特性includes用法修改时间:2026-06-29 02:36:17