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

JavaScript中else if分支未触发问题排查求助

问题原因

当输入空字符串''时,JavaScript会将其隐式转换为数字0,0对5取模结果为0,因此第一个if(x % 5 == 0)条件会被触发,直接执行对应提示,根本不会进入后续的else if分支。只有当点击取消按钮(此时x为null)时,null % 5会得到NaN,NaN == 0不成立,才会走到else if分支,但空字符串的情况被提前拦截了。

修正后的代码
let x = prompt('Enter number');

if(x == '' || x == null){
    alert('Fill the no');
}else if(x % 5 == 0){
    alert('Multiple of 5');
}else{
    alert('Not a multiple of 5')
}

额外优化建议

可以加上类型判断,确保输入的是有效数字,避免非数字输入导致的异常:

let x = prompt('Enter number');

if(x == '' || x == null){
    alert('Fill the no');
}else if(isNaN(Number(x))){
    alert('Please enter a valid number');
}else if(Number(x) % 5 == 0){
    alert('Multiple of 5');
}else{
    alert('Not a multiple of 5')
}

内容的提问来源于stack exchange,提问作者Babai Bose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:57:08