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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:55:17