使用 for 循环和 indexOf 检查单词是否存在时出现令牌错误

token error when checking if a word exist with for loop and indexOf

我正在尝试检查当用户输入任何内容时用户输入中是否有单词“@gmail.com”,如果该单词不存在,则重复问题直到用户输入该单词"@gmail.com" 但我在控制台中收到意外的令牌错误),我刚开始学习循环,但想尝试仅使用 for 循环和 if 语句来尝试这个想法。

for (var userInput = prompt("enter your email"); userInput.indexOf("@gmail.com") === -1); {
    var userInput = prompt("enter your email");
    if (userInput.indexOf("@gmail.com") !== -1) {
        alert("Welcome");
    }
}

据我了解你想做什么:

var userInput;
do {
     userInput = prompt("enter your email");
} while(userInput.indexOf("@gmail.com") === -1)
alert("Welcome");

这可能不是最好的方法。使用这样的脚本,您不会检查“@gmail.com”在哪里,您无法停止或取消等

你的 for 循环语法是错误的。它必须在大括号中包含 3 个语句,如下所示:

for(var i = 0; i < 2; i++) {
  //Do something
}

第一个语句在循环开始时执行一次。 第二条语句检查循环内的代码是否应该被执行。 第三条语句在每次循环后执行。

所以在你的情况下会是:

//We ignore the last statement, but have to keep the semicolon!
for (var userInput = prompt("enter your email"); userInput && userInput.indexOf("@gmail.com") === -1; ) {
    userInput = prompt("enter your email");
    if (userInput && userInput.indexOf("@gmail.com") !== -1) {
        alert("Welcome");
    }
}

这将像您一样使用 for 循环进行循环,但当然 对于此目的,答案更优雅。

希望对您有所帮助。 -头脑