JavaScript新手问题:while循环无法按预期跳出,求break添加位置
解决方法
你只需要在每个满足条件的代码块里,执行console.log之后添加break语句就行。因为break需要放在条件成立时执行的代码逻辑中,才能触发终止循环的效果。
修改后的完整代码:
let parrotRobot = prompt("Hi, Im a robot parrot"); while (true) { parrotRobot = prompt(parrotRobot); if (parrotRobot.toLowerCase() === "stop copying me") { console.log("Aight, Geen probleem"); break; // 满足条件后跳出循环 } else if (parrotRobot.toLowerCase() === "stop acting like a parrot") { console.log("Ok, I liked being a parrot though"); break; // 满足条件后跳出循环 } }
说明:
- 当用户输入的内容匹配任意一个指定语句时,程序会先执行对应的
console.log输出,然后通过break直接终止当前的while(true)无限循环,结束程序。 - 必须把
break写在每个条件的大括号内部,确保只有条件满足时才会触发跳出操作。
内容的提问来源于stack exchange,提问作者matsolord
相关产品推荐
相关产品推荐

