jeudi 8 mars 2018

javascript: evaluating multiple if statements without also running else

i'm trying to throw together a simple javascript page with multiple if statements. the idea is to append to a list based on the evaluation of a stack of if statements. the problem is if any one of them fails, it triggers the else statement. i only want it to trigger else in the case that all of them fail.

<p id="fruit">My fruit basket has: </p>

if (apples) {
        document.getElementById("fruit").innerHTML += "apples";
    }
if (oranges) {
        document.getElementById("fruit").innerHTML += "oranges";
    }
if (bananas) {
        document.getElementById("fruit").innerHTML += "bananas";
    }
else {
        document.getElementById("fruit").innerHTML += "nothing";
}

when i run this and all conditions are met, i'll get:

My fruit basket has: apples oranges bananas

when i run this and no conditions are met, i'll get:

My fruit basket has: nothing

but if any one of the conditions is not met, i'll get:

My fruit basket has: apples nothing

or

My fruit basket has: apples bananas nothing

i've tried using if else, but then it quits after the first 'match'. so in the above example if i have both apples and bananas, using if else will return

My fruit basket has: apples

and not tell me i also have bananas.

question: how do i do this so the else statement is only run in the case that all if statements have failed?

Aucun commentaire:

Enregistrer un commentaire