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;
}
使用示例:

const str = "Hello, world!";
console.log(customIndexOf(str, "world")); // 输出: 7
console.log(customIndexOf(str, "x")); // 输出: -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 arr = [1, 2, 3, 4, 5];
console.log(customArrayIndexOf(arr, 3)); // 输出: 2
console.log(customArrayIndexOf(arr, 6)); // 输出: -1
优化版本(支持 Unicode 和边界检查)
对于字符串实现,可以进一步优化以支持 Unicode 字符和更严格的边界检查:
function robustIndexOf(str, searchValue, fromIndex = 0) {
if (typeof str !== 'string' || typeof searchValue !== 'string') {
throw new TypeError('Input must be strings');
}
if (fromIndex < 0) fromIndex = 0;
if (fromIndex >= str.length || searchValue.length === 0) return -1;
const maxIndex = str.length - searchValue.length;
for (let i = fromIndex; i <= maxIndex; i++) {
if (str.slice(i, i + searchValue.length) === searchValue) {
return i;
}
}
return -1;
}
说明:
- 字符串实现通过逐字符比较来匹配子串。
- 数组实现直接遍历数组元素。
- 优化版本使用
slice方法简化子串匹配,并增加类型检查。






