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

