【发布时间】:2014-07-01 23:03:13
【问题描述】:
我只是不明白 && 和 || 是怎么回事工作。我写了一个小代码来帮助自己,这对我来说没有任何意义。您将单击一个按钮,然后将调用 startGame()。
var startGame = function() {
var quizAnswers = {
name: prompt("What is your name?").toUpperCase(),
age: prompt("What is your age?"),
snack: prompt("What is your favorite type of snack out of the following: ice cream, apple, chips, cookies?").toUpperCase()
};
quizAnswers.confirmAge = function () {
while (isNaN(this.age) === true) {
this.age = prompt("The age that you entered- " + this.age + " -is not a number. Please enter a number.");
};
};
quizAnswers.confirmAge();
quizAnswers.confirmSnack = function () {
while ((this.snack !== "ICE CREAM") && (this.snack !== "APPLE") && (this.snack !== "CHIPS") && (this.snack !== "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is unrecognized. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
};
quizAnswers.confirmSnack();
它将获取姓名、年龄和最喜欢的零食,然后检查年龄是否为数字,输入的零食是否是列出的选项之一。弄乱了 confirmSnack 函数中的 while 循环后,我想出了如何让它工作,如上图所示。但为什么是 && 而不是 ||。有没有办法缩短它:
while (this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is invalid. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
所以问题是解释为什么使用 &&(and) 而不是 ||(or) 以及是否有办法缩短此代码,这样我就不必输入“this.snack!==”四个次。我不是专家,所以请尽量保持简单。
【问题讨论】:
-
尝试大声朗读这些表达式,对“!==”使用“is different from”。很明显,“a 与 b 不同,或 a 与 c 不同”不是您想要的逻辑,因为只要它与 c 不同,a 就可以与 b 相同。
-
这与 JavaScript 无关,更像是数学和逻辑。
标签: javascript logical-operators