js indexof 实现
实现 JavaScript 的 indexOf 方法
JavaScript 的 indexOf 方法用于查找字符串或数组中指定元素的首次出现位置。以下是手动实现该功能的几种方式:
字符串版本的 indexOf
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++) {
if (str[i] === searchValue[0]) {
let match = true;
for (let j = 1; j < searchValue.length; j++) {
if (str[i + j] !== searchValue[j]) {
match = false;
break;
}
}
if (match) return i;
}
}
return -1;
}
数组版本的 indexOf
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;
}
优化版本(支持严格相等)
function strictIndexOf(array, value, fromIndex) {
let index = fromIndex - 1;
const length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
使用示例
const str = "Hello World";
console.log(customIndexOf(str, "World")); // 输出: 6
const arr = [1, 2, 3, 4, 5];
console.log(arrayIndexOf(arr, 3)); // 输出: 2
这些实现方式模拟了原生 indexOf 方法的核心功能,包括:
- 从指定位置开始搜索
- 返回首次匹配的索引
- 未找到时返回 -1
- 支持负数索引(数组版本)
注意这些实现没有完全复制原生方法的所有边界情况处理,但提供了基本功能的实现思路。







