简体   繁体   中英

JavaScript logical operators questions?

I just don't understand how && and || work. I wrote up a small code to help myself out and it just doesn't make any sense to me. You would click a button and the startGame() would be called.

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();

It would get name, age, and favorite snack and then check to see if the age is a number and the snack entered is one of the listed options. After messing with the while loop in the confirmSnack function, I figured out how to make it work, which is displayed above. But why is it && and not ||. And is there a way to shorten it like:

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();
        };

So the questions are to explain why &&(and) is used instead of ||(or) and if there is a way to shorten this code so i don't have to enter "this.snack !==" four times. I'm not an expert so please try to keep it simple.

The && operator is working just fine. This is actually a question of logic, not javascript.

You are asking the question while the answer is different from ALL of the possible answers.

It could be rewritten with || as the follwing:

while (!(this.snack == "ICE CREAM" || this.snack == "APPLE" || this.snack == "CHIPS" || this.snack == "COOKIES"))

Notice the ! operator in the beginning.

A shorter form to write it would be:

answers = ["ICE CREAM", "APPLE", "CHIPS", "COOKIES"];
while (answers.indexOf(this.snack) < 0) { ... }

Here you define a list of possible answers and you want to accept, and check if the answer is among them.

The && and || operators compare boolean values. (Boolean means true/false). That means if you execute 5 == 5 && 6 + 1 == 7 the interpreter does the following things:

  1. Evaluate 5 == 5 . The == operator returns true if both sides are equal (as you probably know). Since 5 == 5 is true , we look at the next value (if it were false, because of short circuit operators, it would return false immediately).

  2. Evaluate 6 + 1 == 7 . This is also true, so the returned value is true .

The && operator does not compare regular values such as "ICE CREAM" (well it does, but it converts it into a boolean value).

Now let's look at the code you provided:

this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")

First, the javascript interpreter executes ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES") . Since all of those values are true, the value of that expression is true . So this comparison is essentially checking this.snack !== true , which is not what you want.

To solve your problem, I would suggest using indexOf . This checks if an element is in an array and returns -1 if there is no element. For example:

var validSnacks = ["ICE CREAM", "APPLE", "CHIPS", "COOKIES"];
while (validSnacks.indexOf(this.snack) === -1) {
    // Do something
}

If you use or(||) , if any of the sub-statements (eg this.snack !== "ICE CREAM") evaluate to true , the entire statement will be true, causing the prompt to be shown.

On the other hand, using and(&&) , all of the sub-statements must be true for the entire statement to evaluate as true, which is the behaviour that you want - you only want the prompt to show if snack is not one of the 4 options.

There is no way to shorten the code in the way you suggest. One thing you could do would be to make an array with the 4 options in it and check if that array contains snack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM