Javascript If Condition with multiple OR and AND

前端 未结 7 827
谎友^
谎友^ 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:07
    if(choice1 && choice2 === "rock" || "paper" || scissors) {
    

    Could anyone give me a short explanation, why the if condition passes every value it gets?

    Because it will be evaluated as

    if ((choice && (choice2 === "rock")) || "paper" || scissors )
    

    which is probably not what you wanted. The non-empty string "paper" is a truthy value, which means it will always fulfill the condition (and due to short-circuit evaluation, the reference error scissors will not be looked at).

    See Check variable equality against a list of values (and its many linked duplicates) for how to do it correctly.

    0 讨论(0)
提交回复
热议问题