Javascript If Condition with multiple OR and AND

前端 未结 7 838
谎友^
谎友^ 2020-12-22 07:33

please have a look on my if condition. I am just refreshing my javascript and I am wondering, how I could check, if the inserted variables, are the ones I want to be used.

7条回答
  •  借酒劲吻你
    2020-12-22 08:02

    The issue is your condition will always evaluate to true since the || "paper" condition is going to return a truth-y value. That alone makes the entire condition true, since the values are OR'd, so it always passes. You're checking for choice1 && choice2 === "rock", which isn't really written correctly. As for || scissors that will be false since scissors is undefined here.

    Consider taking this approach instead:

    var validOptions = ["rock", "paper", "scissors"];
    if(validOptions.indexOf(choice1) > -1 && validOptions.indexOf(choice2) > -1) {
        // now compare choice1 and choice2 to determine the winner
    } else {
        alert("Something went wrong");
    }
    

    Note that the solution shown doesn't trim the user input or account of case sensitivity. To address that you could use a regex with the ignore-case flag:

    var re = /\b(?:rock|paper|scissors)\b/i;
    if (re.test(choice1) && re.test(choice2)) {
        // ...
    }
    

提交回复
热议问题