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
相关产品推荐
相关产品推荐

