if statement in javascript always true

前端 未结 5 873
無奈伤痛
無奈伤痛 2020-12-11 18:54

So, I have the code, its not done, but all i want it to do is display one alert box if I write the word \'help\', and say something else if anything else is entered.

<
相关标签:
5条回答
  • 2020-12-11 19:01

    The problem is this line:

     if (reply === 'help' || 'Help')
    

    Because in JavaScript, objects and non-empty strings evaluate to true when used as a boolean. There are a couple of exceptions to this when using ==

     if("0") // true
     if("0" == true) // false
    

    In general, it's not a good idea to use == or raw variables in if statements.

    As others have pointed out, use

    if (reply === 'help' || reply === 'Help')
    

    Or better:

    if (typeof reply === 'string' && reply.toLowerCase() === 'help')
    

    instead.

    0 讨论(0)
  • 2020-12-11 19:03

    The reason why it always pops up is that reply === 'help' || 'Help' evaluates as (reply === 'Help') || ('Help'). The string literal Help is always truthy in Javascript hence it always evaluates to truthy.

    To fix this you need to compare reply to both values

    if (reply === 'help' || reply === 'Help') {
      ...
    }
    

    Or if you want any case variant of help use a regex

    if (reply.match(/^help$/i)) {
      ...
    }
    
    0 讨论(0)
  • 2020-12-11 19:05

    The problem is here:

    if (reply === 'help' || 'Help') // <-- 'Help' evaluates to TRUE
                                    //      so condition is always TRUE
    

    The equality operator doesn't "distribute", try

    if (reply === 'help' || reply === 'Help')
    
    0 讨论(0)
  • 2020-12-11 19:10
    if (reply === 'help' || 'Help')
    

    should be:

    if (reply === 'help' || reply === 'Help')
    

    since 'Help' is "truthy" and so the first part of the if will always be entered.

    Of course, even better would be to do a case-insensitive comparison:

    if (reply.toLowerCase() === 'help')
    

    Example: http://jsfiddle.net/qvEPe/

    0 讨论(0)
  • 2020-12-11 19:21

    Just change this: if (reply === 'help' || 'Help')

    To this: if (reply === 'help' || reply === 'Help')

    The or statement was not comparing the variable.

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