javascript中的if语句始终为true

if statement in javascript always true

本文关键字:true 语句 中的 if javascript      更新时间:2023-09-26

所以,我有代码,它还没有完成,但我只想让它在写单词"help"时显示一个警告框,如果输入了其他内容,则显示其他内容。

function prompter() {
var reply = prompt("This script is made to help you learn about new bands, to view more info, type help, otherwise, just click OK") 
if (reply === 'help' || 'Help')
  {
  alert("This script helps you find new bands. It was originally written in Python 3.0.1, using Komodo IDE, but was then manually translated into Javascript. Please answer the questions honestly. If you have no opinion on a question, merely press OK without typing anything.")
  }
else
  {
  alert("Press OK to continue")
  }
};

但是,不管怎样,即使你按下取消键,第一个提醒框也会弹出!我该怎么解决这个问题???

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

应该是:

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

由于CCD_ 1是"truthy",因此CCD_。

当然,做一个不区分大小写的比较会更好:

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

示例:http://jsfiddle.net/qvEPe/

问题就在这里:

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

相等运算符不"分布",请尝试

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

它总是弹出的原因是reply === 'help' || 'Help'计算为(reply === 'Help') || ('Help')。字符串文字Help在Javascript中始终是truthy,因此它的计算结果始终为truthy。

要解决此问题,您需要将reply与的两个值进行比较

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

或者,如果您想要任何情况下的帮助变体,请使用regex

if (reply.match(/^help$/i)) {
  ...
}

只需更改即可:if (reply === 'help' || 'Help')

对此:if (reply === 'help' || reply === 'Help')

or语句未对变量进行比较。

问题是这一行:

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

因为在JavaScript中,对象和非空字符串在用作布尔值时计算结果为true。使用'Help'0 时有几个例外

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

通常,在if语句中使用==或原始变量不是一个好主意。

正如其他人所指出的,使用

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

或者更好:

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

相反。