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><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill11083" title="Java调试"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dbae7c507.jpg" alt="Java调试" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill11083" title="Java调试">Java调试</a>
<p>通过 JDWP 实现 Java 远程调试:连接远程 JVM、设置断点、单步执行代码、查看变量值、获取调用栈。适用于需要调试远程 Java 应用、排查运行时状态、追踪代码执行流程的场景。
术语注解
JDWP:Java Debug Wire Protocol,Java 调试有线协议(Java 远程调试底层通信协议)
remote JVM:远程 Java 虚拟机
step through code:代码单步调试(步入 / 步过 / 步出调试)
inspect variables:变量查看 / 变量检视
stac</p>
</div>
<a href="/xiazai/skill11083" title="Java调试" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>封装成可复用的函数
把逻辑抽成函数,支持字符串和数组(因为数组的 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 < arr.length; i++) {
if (arr[i] === "a") result.push(i);
}
console.log(result); // [0, 2, 4]
字符串同理,可用 str[i] 或 str.charAt(i) 逐字符比较。

















