js indexof的实现
JavaScript 的 indexOf 实现
JavaScript 的 indexOf 方法用于查找字符串或数组中指定元素的首次出现位置。以下是其实现原理及自定义实现方式。
字符串的 indexOf
String.prototype.indexOf 用于查找子字符串在父字符串中的位置,若未找到返回 -1。
自定义实现:
function customIndexOf(str, searchValue, fromIndex = 0) {
if (fromIndex < 0) fromIndex = 0;
if (fromIndex >= str.length) return -1;
for (let i = fromIndex; i < str.length; i++) {
let match = true;
for (let j = 0; j < searchValue.length; j++) {
if (str[i + j] !== searchValue[j]) {
match = false;
break;
}
}
if (match) return i;
}
return -1;
}
示例:
const str = "Hello, world!";
console.log(customIndexOf(str, "world")); // 输出: 7
数组的 indexOf
Array.prototype.indexOf 用于查找元素在数组中的位置,若未找到返回 -1。
自定义实现:
function arrayIndexOf(arr, searchElement, fromIndex = 0) {
if (fromIndex < 0) fromIndex = Math.max(0, arr.length + fromIndex);
for (let i = fromIndex; i < arr.length; i++) {
if (arr[i] === searchElement) return i;
}
return -1;
}
示例:

const arr = [1, 2, 3, 4, 5];
console.log(arrayIndexOf(arr, 3)); // 输出: 2
关键点说明
- 字符串匹配:通过双重循环比较子字符串与父字符串的每个字符。
- 数组匹配:直接遍历数组元素,使用严格相等(
===)比较。 - 负数索引处理:若
fromIndex为负数,从末尾开始计算位置。
注意事项
- 原生
indexOf使用更高效的算法(如 Boyer-Moore),上述实现仅为简化版。 - 对于大型数据,建议直接使用原生方法以获得更好性能。






