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

JavaScript条件判断逻辑错误求助:驾照年龄判断异常

问题分析与修复

你的代码逻辑错误在于只把“满21岁且持有驾照”判定为可驾驶,完全忽略了“不满21岁但持有驾照”的合法场景。对照你期望的四个规则,核心判定逻辑其实是:只要持有驾照(输入Y)就可以驾驶,无驾照(输入N)则不能驾驶,年龄并不影响这个权限。

修复后的代码

<meta charset="UTF-8">

<script>
    function skipLine() {
        document.write("<br>");
    }

    function print(phrase) {
        document.write(phrase);
        skipLine();
    }

    var age = parseInt(prompt("What's your age?"));
    var haveLicense = prompt("Do you have drivers licence Y or N");

    // 匹配你期望的所有场景:输入Y就可驾驶,否则不可
    if(haveLicense === "Y") {
        print("You can drive");
    } else {
        print("You can't drive");
    }
</script>

额外优化建议

  • 统一处理输入大小写,避免用户输入小写y不被识别:
    var haveLicense = prompt("Do you have drivers licence Y or N").toUpperCase();
    
  • 增加无效输入的提示,覆盖用户输入非Y/N的情况:
    var haveLicense = prompt("Do you have drivers licence Y or N").toUpperCase();
    if(haveLicense === "Y") {
        print("You can drive");
    } else if(haveLicense === "N") {
        print("You can't drive");
    } else {
        print("Invalid input, please enter Y or N");
    }
    
  • 增加年龄输入有效性判断,避免parseInt返回NaN:
    var age = parseInt(prompt("What's your age?"));
    if(isNaN(age)) {
        print("Invalid age input");
    } else {
        // 后续驾照判断逻辑
    }
    

内容的提问来源于stack exchange,提问作者jose andres aldana santillana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:15:42