我开始了JavaScript入门课程,而我们正在研究逻辑运算符。我的脚本的目标是在满足一些条件的情况下打印一条语句。
我有3个变量(例如x,y,z),如果x = a ||,则需要将其打印到控制台。 b AND y = c || d AND 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.");
}
它需要有香草或巧克力&&锥或碗&&撒有花生才能真实印刷。使用我的代码,它可以打印变量中的任何值,无论它们是什么。
我的代码是否存在语法错误?还是您不能在一句话中比较那么多事情?正如我所说的,这是一门入门课程,所以我无法想象这将是如此复杂。只是有些东西没有在我的大脑中触发。大声笑
任何帮助/解释将不胜感激。
提前谢谢!
答案 0 :(得分:3)
问题是您如何使用OR条件。在JS中,当您使用不同于undefined
或null
或0
或""
或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.");
}
答案 1 :(得分:1)
有一些规则描述了如何将多个比较链接在一起。
这些规则被称为precedence规则,但是通常使用额外的括号将比较分组在一起比较容易,这样您就不必担心优先级规则了。这是带有正确括号的if语句:
if ((flavor === "vanilla" || flavor === "chocolate") && (vessel === "cone" || vessel === "bowl") && (toppings === "sprinkles" || toppings === "peanuts"))