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

为何JS简单if语句未输出预期结果?新手技术求助

问题分析与解决

核心问题:条件表达式写法错误

你写的if (stationery == "pen" || "pencil")逻辑完全不对。JavaScript里的逻辑或运算符||需要左右两边都是完整的布尔判断表达式,而你这里右边直接写了"pencil"——这是一个非空字符串,在JS里属于truthy(真值),不管左边的stationery == "pen"是否成立,整个||表达式的结果都会是true,所以不管你把stationery改成什么值,if分支都会执行,else永远不会触发。

正确的条件写法

要判断变量是否等于多个值中的任意一个,得给每个值都写完整的判断:

let stationery = "pen";
if (stationery == "pen" || stationery == "pencil") { 
    console.log("You have enough stationery to write the exam.");
}
else {
    console.log("You do not have sufficient stationery to write the exam.");
}

如果需要判断的值较多,也可以用更简洁的数组包含判断:

let stationery = "pen";
if (["pen", "pencil"].includes(stationery)) { 
    console.log("You have enough stationery to write the exam.");
}
else {
    console.log("You do not have sufficient stationery to write the exam.");
}

和let/var无关

你担心的let/var差异和这个问题完全没关系,两者只是变量作用域、提升规则的区别,不影响条件判断的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:45:38