You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for of与indexOf遍历字符串查找空格索引结果重复如何解决?

问题原因

  • String.indexOf()方法默认从字符串起始位置开始查找,仅返回第一个匹配项的索引:你在循环中每次匹配到空格时调用tipo.indexOf(char),参数固定为空格,所以永远返回第一个空格的索引,和当前遍历的位置无关。
  • for...of遍历字符串时默认仅返回每个位置的字符值,不会携带当前遍历的下标信息,你无法从循环变量char中获取当前位置。

修复方案

方案1:搭配entries()方法获取遍历下标

直接通过字符串内置的entries()方法同时拿到当前遍历的索引和字符,不需要调用indexOf:

const tipo = 'Quimes Bajo Cero  ';

for (const [index, char] of tipo.entries()) {
  char === ' ' ? console.log(index) : console.log('this character is not empty space');
}

方案2:用indexOf的第二个参数实现批量查找

不需要逐字符遍历,通过给indexOf传入第二个「起始查找位置」参数,每次找到空格后从下一位继续查找,性能更高:

const tipo = 'Quimes Bajo Cero  ';
let findIndex = tipo.indexOf(' ');

while (findIndex !== -1) {
  console.log(findIndex);
  findIndex = tipo.indexOf(' ', findIndex + 1);
}

内容的提问来源于stack exchange,提问作者Julio Rodríguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 17:15:02