JavaScript中indexOf结合while循环可找出所有匹配索引:初始化fromIndex=0,循环调用indexOf(searchValue, fromIndex),每次将fromIndex设为上一索引+1,直至返回-1;可封装为支持字符串和数组的findAllIndices函数,但需注意空字符串导致死循环及对象查找不适用等问题。

JavaScript 中 indexOf 本身只返回第一个匹配项的索引,但可以结合循环(如 while)反复调用,从上一次找到位置的后一位继续搜索,从而找出所有匹配索引。
用 while 循环配合 fromIndex 参数
indexOf(searchValue, fromIndex) 的第二个参数指定开始查找的位置。每次找到一个索引后,把起始位置设为 index + 1,就能跳过已找到的项,继续往后找。
- 初始化
fromIndex = 0 - 循环条件:
indexOf返回值不等于-1 - 每次找到后,把新
fromIndex设为当前索引加 1
示例:
const str = "abababa";
const search = "a";
const indices = [];
let idx = -1;
<p>while ((idx = str.indexOf(search, idx + 1)) !== -1) {
indices.push(idx);
}</p><p>console.log(indices); // [0, 2, 4, 6]</p>封装成可复用的函数
把逻辑抽成函数,支持字符串和数组(因为数组的 indexOf 行为类似):
- 对数组:需注意
indexOf对引用类型(如对象)不适用,仅适合原始值 - 函数接收目标值、源数据、可选起始位置
- 返回包含所有索引的数组
简单实现:
function findAllIndices(arrOrStr, target, from = 0) {
const indices = [];
let i = from - 1;
<p>while ((i = arrOrStr.indexOf(target, i + 1)) !== -1) {
indices.push(i);
}</p><p>return indices;
}</p><p>// 使用
console.log(findAllIndices([1, 2, 1, 3, 1], 1)); // [0, 2, 4]
console.log(findAllIndices("hello world", "l")); // [2, 3, 9]</p>注意边界与性能问题
这种写法简洁直接,但要注意几点:
- 空字符串在非空字符串中会匹配到每个位置(包括末尾),
"abc".indexOf("", 3)返回3,容易陷入死循环,使用前建议校验searchValue是否为空 - 对超长数据或高频调用场景,可考虑用正则(
RegExp.prototype.exec配合g标志)或for循环手动比对,更可控 - 数组中查找对象或复杂结构,请改用
findIndex+forEach或map等方式
替代方案:用 for 循环手动遍历(更直观)
如果想避免 indexOf 的隐式行为,直接用 for 更易理解,尤其适合自定义匹配逻辑:
const arr = ["a", "b", "a", "c", "a"]; const result = []; for (let i = 0; i
字符串同理,可用 str[i] 或 str.charAt(i) 逐字符比较。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











