[removed] How can I simplify an if-statement with multiple OR conditions?

前端 未结 6 957
半阙折子戏
半阙折子戏 2021-01-16 17:22

Sorry if I\'ve made mistakes writing this post. I\'m new here and I don\'t know how this works, hope I learn quick. I am also new at JavaScript.

So the question is:

6条回答
  •  一整个雨季
    2021-01-16 17:46

    Because JavaScript has short circuit evaluation and your strings are truthy then you need to use the second approach or what you referred to as "the normal way".

    The first way does not work because you end up evaluating the wrong thing. Evaluation works like this:

    var result = 0 || "zero" ;

    • 0 is evaluated and determined to be falsy.
    • "zero" is evaluated as truthy and becomes the result.

    var result = "zero" || 0 ;

    • "zero" is evaluated and determined to be truthy and returned as the result.
    • 0 is not evaluated because short circuit evaluation.

    In your original code:

    if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)){};

    The operator associativity of || is left to right. Parenthesis are evaluated inner to outer.

    (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo) is evaluated first. Because of the rules we already discussed the result becomes codeSwitch:

    • codeSwitch || codeSwitchBG becomes codeSwitch
    • codeSwitch || codeBlur becomes codeSwitch
    • codeSwitch || codeShowInfo becomes codeSwitch

    So you end up evaluating:

    if(codePrompt == codeSwitch)

    Which of course is wrong.

提交回复
热议问题