简体   繁体   English

为什么这个和/或场景评估为假?

[英]Why does this and/or scenario evaluate to false?

Why does this return false ? 为什么返回false

var flavor = "chocolate";
console.log(flavor == ("vanilla" || "chocolate")); 

and if I type instead: 如果我改为输入:

var flavor = "chocolate";
console.log(flavor == ("vanilla" && "chocolate"));

it returns true . 它返回true This doesn't make sense to me because logically, flavor cannot equal both chocolate and vanilla. 这对我来说没有任何意义,因为从逻辑上讲,风味不能同时等于巧克力和香草。 Can someone help me understand how I should be thinking through this? 有人可以帮助我了解我应该如何思考吗?

(flavor == ("vanilla" || "chocolate")) returns false because ("vanilla" || "chocolate") returns as "vanilla" , so you're actually comparing "chocolate" == "vanilla" , which returns false . (flavor == ("vanilla" || "chocolate"))返回false,因为("vanilla" || "chocolate")返回为"vanilla" ,因此您实际上是在比较"chocolate" == "vanilla" ,返回false

(flavor == ("vanilla" && "chocolate")) returns true because ("vanilla" && "chocolate") returns as "chocolate" , so "chocolate" == "chocolate" obviously returns true . (flavor == ("vanilla" && "chocolate"))返回true,因为("vanilla" && "chocolate")返回为"chocolate" ,因此"chocolate" == "chocolate"显然返回true

I think what you actually want is (flavor == "vanilla" || flavor == "chocolate") and (flavor == "vanilla" && flavor == "chocolate") . 我认为您真正想要的是(flavor == "vanilla" || flavor == "chocolate")(flavor == "vanilla" && flavor == "chocolate") Give that a try :) 试试看:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM