Udacity冰淇淋测验 - Javascript声明/条件

时间:2018-05-15 07:27:11

标签: javascript variables boolean

在下面的测验中需要一些帮助。



/*
 * Programming Quiz: Ice Cream (3-6)
 *
 * Write a single if statement that logs out the message:
 * 
 * "I'd like two scoops of __________ ice cream in a __________ with __________."
 * 
 * ...only if:
 *   - flavor is "vanilla" or "chocolate"
 *   - vessel is "cone" or "bowl"
 *   - toppings is "sprinkles" or "peanuts"
 *
 * We're only testing the if statement and your boolean operators. 
 * It's okay if the output string doesn't match exactly.
 */

// change the values of `flavor`, `vessel`, and `toppings` to test your code
var flavor = "strawberry";
var vessel = "hand";
var toppings = "cookies";

// Add your code here
if (flavor === "vanilla" || "chocolate" && vessel === "cone" || "bowl" && toppings === "prinkles" || "peanuts"){
    console.log("I'd like two scoops of " + flavor + " ice cream in a " + vessel + " with " + toppings + ".");
}
else {
    
}




我似乎无法找到一种方法,只有在符合条件的情况下才能打印语句。此时,每当我使用在条件中定义的的变量时;无论如何它都会在控制台中打印出来。 我想找到一种方法来防止这种情况。 希望这一切都有道理。任何帮助将非常感激。 谢谢!

3 个答案:

答案 0 :(得分:1)

尝试如下:

var flavor = "vanilla";
var vessel = "bowl";
var toppings = "peanuts";

if (
    ["vanilla","chocolate"].includes(flavor)
    && ["cone", "bowl"].includes(vessel)
    && ["sprinkles", "peanuts"].includes(toppings)) {

       console.log("I'd like two scoops of %s ice cream in a %s with %s toppings.", 
                    flavor, vessel, toppings);
}
  

Codepen demo

有关includes() on MDN

的参考资料

答案 1 :(得分:1)

您正在使用=== 'str1' || 'str2之类的条件检查,这是不正确的。

您可以明确指定所有条件,以便明白理解。

if ((flavor === "vanilla" || flavor === "chocolate") && (vessel === "cone" || vessel === "bowl") && (toppings === "prinkles" || toppings === "peanuts")){

答案 2 :(得分:1)

var flavor = "chocolate"||"vanilla";
var vessel = "bowl"||"cone";
var toppings = "sprinkles"||"peanuts";



if(( flavor==="chocolate"|| flavor==="vanilla" ) && (vessel==="bowl"||vessel==="cone") && (toppings==="peanuts" ||toppings==="sprinkles")){
    console.log("I'd like two scoops of " + flavor + " ice cream in a " + vessel + " with " + toppings);
    
}