Udacity冰淇淋JavaScript测验:条件判断逻辑错误求助
问题分析与修正方案
我一眼就看出你的代码里几个关键问题,导致不符合条件时也会输出语句:
核心错误点
- 错误的条件表达式写法:比如
flavor === "vanilla" || "chocolate"这种写法完全不对。"chocolate"是一个非空字符串,在布尔判断中会被直接判定为true,所以不管flavor是什么值,这部分条件都会成立。正确的写法应该是对每个可选值都做完整的相等判断:flavor === "vanilla" || flavor === "chocolate"。 - 运算符优先级混乱:
&&的优先级比||高,原代码的条件会被错误地分组执行,导致三个属性的条件没有同时被校验。必须用括号把每个属性的可选值条件包裹起来,确保三个属性的条件全部满足才会执行输出。 - 拼写错误:你把
"sprinkles"写成了"prinkles",这会导致正确的配料值无法匹配。
修正后的代码
/* * 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" || 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。 - 修正了配料的拼写错误,保证匹配逻辑正确。
你可以修改 flavor、vessel 和 toppings 的值来测试,比如把三个值都设为符合要求的选项,就能看到正确输出;只要有一个不符合,就不会执行输出语句。
内容的提问来源于stack exchange,提问作者fdaffdsafdsafdsafdsafdsafdsfsa
相关产品推荐
相关产品推荐

