【问题标题】:my indexOf keeps finding the character at the same postition how can i solve it?我的 indexOf 一直在同一位置找到字符我该如何解决?
【发布时间】:2023-04-07 20:59:02
【问题描述】:
for(let j=0; j<=z;j++)
  {
  if( text[i+1].indexOf(y[j]) > -1 )
    {
    con++;
    temp = (text[i+1].indexOf(y[j]));
    text[i+1].substring(temp);
    console.log(text[i+1].indexOf(y[j]))

当数组y 的一个字母在text[i+1] 的字符串中时,这是代码计数,但不是通过整个单词来查找其他位置的字母,而是停留在它找到的第一个位置。

例子:

 text[i+1] = 'debefeene' 
 y = ['e','e','e','e']
 // My expected output would be:
1
3
5
6
8
 // The actual output is:
1
1
1
1

我尝试使用子字符串,但没有真正起作用。

z 等于字符串 text[i+1]

的长度

【问题讨论】:

  • 请发布完整的代码。例如,什么是“骗局”?我们无法猜测您未发布的代码。
  • String.prototype.indexOf 将从第二个参数的指定索引开始查找第一个匹配项。默认为0。因此,如果您想要下一次出现,则必须使用最后一次出现的索引作为它的第二个参数。
  • con 只是一个计数器
  • @MinusFour 谢谢,我用 lastIndexOf 替换 indexOf 但它一直重复我找到了这段代码,但我有点困惑,你能解释一下吗? :D developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 我应该说“以前发生过”。您不需要使用lastIndexOf。查看String.prototype.indexOf 的文档。查看第二个参数。

标签: javascript arrays for-loop substring indexof


【解决方案1】:

我不明白你尝试了什么。这就是为什么我无法判断您的代码有什么问题。看看我的解决方案。这是不言自明的。第二个“如果”不是必需的。如果没有任何要搜索的项目,我只是添加它以停止循环。

let text = "debefeene"
let find = ['e','e','e','e', 'e'];

let positions = [];

for(let i = 0; i < text.length; i++) {
  if (text[i] == find[0]) {
    positions.push(i);
    find.pop();
  }
  if (!find.length) break;
}

console.log(positions);

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2020-01-02
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多