if javascript中的语句总是如此

时间:2012-02-15 23:24:51

标签: javascript if-statement prompt

所以,我有代码,没有完成,但我想要它做的就是显示一个警告框,如果我写“帮助”,并说出其他什么,如果输入其他东西。

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")
  }
};

但是,无论发生什么,即使你按下取消,弹出第一个警告框也会发生什么! 我该怎么办?

5 个答案:

答案 0 :(得分:12)

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

应该是:

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

因为'Help'是“真实的”,因此始终会输入if的第一部分。

当然,更好的做法是进行不区分大小写的比较:

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

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

答案 1 :(得分:2)

问题在于:

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

等于运算符不“分发”,请尝试

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

答案 2 :(得分:1)

它总是弹出的原因是reply === 'help' || 'Help'评估为(reply === 'Help') || ('Help')。字符串文字Help在Javascript中始终是真实的,因此它总是评估为真实。

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

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

或者,如果您想要帮助的任何案例变体使用正则表达式

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

答案 3 :(得分:1)

改变这个: if (reply === 'help' || 'Help')

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

or语句没有比较变量。

答案 4 :(得分:0)

问题在于这一行:

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

因为在JavaScript中,对象和非空字符串在用作布尔值时会求值为true。使用==

时,有几个例外
 if("0") // true
 if("0" == true) // false

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

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

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

或更好:

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

代替。