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 customArrayIndexOf(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 str = "Hello, world!";
console.log(customIndexOf(str, "world")); // 输出: 7
const arr = [1, 2, 3, 4, 5];
console.log(customArrayIndexOf(arr, 3)); // 输出: 2
注意事项
- 字符串版本支持多字符搜索,而数组版本仅支持单个元素搜索。
- 两个实现均支持可选的
fromIndex参数,用于指定开始搜索的位置。 - 如果未找到目标值,函数返回
-1,与原生的indexOf行为一致。 - 数组版本处理负数的
fromIndex时,会从数组末尾开始计算位置。







