if statement in javascript always true

前端 未结 5 879
無奈伤痛
無奈伤痛 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条回答
  •  猫巷女王i
    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)) {
      ...
    }
    

提交回复
热议问题