if statement in javascript always true

前端 未结 5 876
無奈伤痛
無奈伤痛 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.

提交回复
热议问题