首页 > 解决方案 > indexOf 的简单算法在 JS 中不起作用

问题描述

我的任务是查找并输出输入的标签/单词在句子中的位置。控制台给了我那个地方 var 没有定义。我应该怎么办?非常感谢!

var sentence = prompt("Enter you sentence");
var word = prompt("Enter the tabs/word you looking for");
var counter = 0;
var place = stntence.indexOf(word, counter);

if (stntence.indexOf(word) != -1) {
  while (place != -1) {
    if (place != -1) {
      console.log("The place of the word/tab is: " + place);
      counter = place++;
    } else {
      console.log("That's all")
    }
  }
} else {
  console.log("the word/tabs are not exist in the sentence");
}

标签: javascript

解决方案


除了 的错字stntence !== sentence,您可以利用计数器并通过直接在while条件中分配位置来使用缩短的方法。

var sentence = prompt("Enter you sentence"),
    word = prompt("Enter the tabs/word you looking for"),
    counter = 0,
    place = -1;

while ((place = sentence.indexOf(word, place + 1)) != -1) {
    console.log("The place of the word/tab is: " + place);
    counter++;
}

if (counter) {
    console.log("That's all");
} else {
    console.log("the word/tabs are not exist in the sentence");
}


推荐阅读