js includes实现原理
JavaScript includes 方法实现原理
includes 方法是 JavaScript 中用于检查数组或字符串是否包含特定元素的工具。其实现原理可以分解为以下几个关键点:
数组的 includes 方法
数组的 includes 方法用于检查数组中是否包含某个值。其实现逻辑如下:

- 遍历数组的每个元素,从起始索引(默认为 0)开始。
- 使用严格相等(
===)比较目标值与当前元素。 - 如果找到匹配项,立即返回
true;否则遍历结束后返回false。
示例代码实现:

Array.prototype.customIncludes = function(searchElement, fromIndex = 0) {
const length = this.length;
fromIndex = fromIndex >= 0 ? fromIndex : Math.max(0, length + fromIndex);
for (let i = fromIndex; i < length; i++) {
if (this[i] === searchElement) {
return true;
}
}
return false;
};
字符串的 includes 方法
字符串的 includes 方法用于检查字符串中是否包含某个子串。其实现逻辑如下:
- 从起始索引(默认为 0)开始搜索子串。
- 如果子串长度加上起始索引超过字符串长度,直接返回
false。 - 使用逐字符匹配的方式检查子串是否存在。
示例代码实现:
String.prototype.customIncludes = function(searchString, position = 0) {
const str = this;
const searchLength = searchString.length;
const strLength = str.length;
position = position >= 0 ? position : Math.max(0, strLength + position);
if (position + searchLength > strLength) {
return false;
}
for (let i = position; i <= strLength - searchLength; i++) {
let match = true;
for (let j = 0; j < searchLength; j++) {
if (str[i + j] !== searchString[j]) {
match = false;
break;
}
}
if (match) {
return true;
}
}
return false;
};
注意事项
includes方法对NaN的处理与普通严格相等不同。数组的includes可以正确识别NaN,而indexOf不能。- 字符串的
includes方法区分大小写。 - 性能上,
includes的时间复杂度为 O(n),但对于大型数据可能需要优化。






