js includes实现原理
JavaScript includes 方法实现原理
Array.prototype.includes 和 String.prototype.includes 是 JavaScript 中常用的方法,用于判断数组或字符串是否包含特定元素或子串。以下是它们的实现原理和细节。
数组的 includes 方法
Array.prototype.includes 用于检查数组是否包含某个值,返回布尔值。其实现原理可以概括为:
- 遍历数组元素,使用严格相等(
===)比较目标值和当前元素。 - 如果找到匹配项,立即返回
true。 - 如果遍历结束未找到匹配项,返回
false。 - 可以指定起始搜索位置(第二个参数)。
示例实现(模拟 includes 的核心逻辑):

function arrayIncludes(array, searchElement, fromIndex = 0) {
const length = array.length;
fromIndex = fromIndex >= 0 ? fromIndex : Math.max(0, length + fromIndex);
for (let i = fromIndex; i < length; i++) {
if (array[i] === searchElement) {
return true;
}
}
return false;
}
字符串的 includes 方法
String.prototype.includes 用于检查字符串是否包含子串,返回布尔值。其实现原理如下:
- 在字符串中搜索子串,如果找到则返回
true,否则返回false。 - 可以指定起始搜索位置(第二个参数)。
- 内部使用字符串匹配算法(如朴素算法或更高效的算法)。
示例实现(模拟 includes 的核心逻辑):

function stringIncludes(str, searchString, position = 0) {
if (position < 0) position = 0;
if (position >= str.length) return false;
return str.indexOf(searchString, position) !== -1;
}
注意事项
- 严格相等:
includes使用===进行比较,不会进行类型转换。 - NaN 处理:数组的
includes能正确识别NaN([NaN].includes(NaN)返回true),而indexOf不能。 - 性能:对于大型数组或字符串,
includes的时间复杂度为 O(n),但实际性能可能因引擎优化而异。
使用示例
数组示例:
const arr = [1, 2, 3, NaN];
console.log(arr.includes(2)); // true
console.log(arr.includes(NaN)); // true
字符串示例:
const str = 'Hello, world!';
console.log(str.includes('world')); // true
console.log(str.includes('WORLD')); // false(区分大小写)
通过理解这些原理,可以更高效地使用 includes 方法并避免常见错误。






