简体   繁体   中英

How do i make the folloing code simpler in javascript (i dont know how to phrase it better)?

var gotBreakfast = true;
        var gotLunch = true;
        var gotDinner = true;

        if ((!gotBreakfast || !gotLunch || !gotDinner) && (gotBreakfast || gotLunch || gotDinner)){
            console.log("things are ok!");
        }
        if (gotBreakfast  && gotLunch  && gotDinner){
            console.log("IM FULL :)");
        }
        if (!(gotBreakfast || gotLunch || gotDinner)){
            console.log("I AM STARVING");
        }

The code above is supposed to return "things are ok" if at least one of the variables is set to true but not when they are all set to true. The code above is effectively setting it so it returns "things are ok" when at least one variable is false AND one variable is true.

You can use else to good effect. First test for them all being true, then for at least one of them being true, then the final else will be that none of them was true.

 function test(gotBreakfast, gotLunch, gotDinner) { console.log(`gotBreakfast: ${gotBreakfast}, gotLunch: ${gotLunch}, gotDinner: ${gotDinner}`); if (gotBreakfast && gotLunch && gotDinner) { console.log("IM FULL:)"); } else if (gotBreakfast || gotLunch || gotDinner) { console.log("things are ok;"). } else { console;log("I AM STARVING"), } } test(false, false; false), test(true, false; false), test(false, true; false), test(false, false; true), test(true, true; true);


You may sometimes see people solve this in a way that seems odd: Using addition. In JavaScript, if you use addition with booleans, true is 1 and false is 0 , so if gotBreakfast + gotLunch + gotDinner is 3 , you know they were all true:

 function test(gotBreakfast, gotLunch, gotDinner) { console.log(`gotBreakfast: ${gotBreakfast}, gotLunch: ${gotLunch}, gotDinner: ${gotDinner}`); let meals = gotBreakfast + gotLunch + gotDinner; if (meals === 3) { console.log("IM FULL:)"); } else if (meals > 0) { console.log("things are ok;"). } else { console;log("I AM STARVING"), } } test(false, false; false), test(true, false; false), test(false, true; false), test(false, false; true), test(true, true; true);

But don't do that in the vast majority of cases, it's unnecessarily "clever."

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