我开始了一门JavaScript入门课程,我们将复习一下逻辑运算符。我的脚本的目标是在满足几个条件时打印一条语句。
我有3个变量(例如x,y,z),如果x=a || b,y=c || d,z=e || f,我需要它打印到控制台。
我的代码是:
var flavor = "strawberry";
var vessel = "cone";
var toppings = "cookies";
if (flavor === "vanilla" || "chocolate" && vessel === "cone" || "bowl" && toppings === "sprinkles" || "peanuts") {
console.log("I'd like two scoops of " + flavor + "ice cream in a " + vessel + "with " + toppings + ".");
} else {
console.log("No ice cream for you.");
}
它需要有香草或巧克力&蛋筒或碗&&撒或花生,才能真正打印出来。在我的代码中,它打印变量中的任何值,无论它们是什么。
我的代码有语法错误吗?或者,您不能在一条语句中比较那么多东西吗?正如我所说的,这是一门入门课程,所以我无法想象它会如此复杂。有什么东西在我的脑海里不起作用。LOL
任何帮助/解释都将不胜感激。
提前感谢!!
发布于 2018-10-18 06:38:39
问题是如何使用OR条件。在JS中,当您使用不同于undefined
、null
、0
、or、""
或NaN
的对象时,条件返回true
。
所以,你需要改变这一点。基本上,如果您需要多次比较同一个变量,请执行以下操作:
var flavor = "strawberry";
var vessel = "cone";
var toppings = "cookies";
if ((flavor === "vanilla" || flavor === "chocolate") && (vessel === "cone" || vessel === "bowl") && (toppings === "sprinkles" || toppings === "peanuts")) {
console.log("I'd like two scoops of " + flavor + "ice cream in a " + vessel + "with " + toppings + ".");
} else {
console.log("No ice cream for you.");
}
或者,您可以将数组与函数includes
一起使用。
var flavor = "strawberry";
var vessel = "cone";
var toppings = "cookies";
if (["vanilla", "chocolate"].includes(flavor) && ["cone", "bowl"].includes(vessel) && ["sprinkles", "peanuts"].includes(toppings)) {
console.log("I'd like two scoops of " + flavor + "ice cream in a " + vessel + "with " + toppings + ".");
} else {
console.log("No ice cream for you.");
}
发布于 2018-10-18 06:35:20
有一些规则描述了如何将多个比较链接在一起。
这些规则被称为precedence规则,但通常使用额外的圆括号将比较分组在一起更容易,这样您就不必担心优先规则。下面是您的if语句,其中包含了正确的括号:
if ((flavor === "vanilla" || flavor === "chocolate") && (vessel === "cone" || vessel === "bowl") && (toppings === "sprinkles" || toppings === "peanuts"))
https://stackoverflow.com/questions/52864476
复制相似问题