javascript 中的 if 语句始终为真 [英] if statement in javascript always true

查看:36
本文介绍了javascript 中的 if 语句始终为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有代码,它没有完成,但我想要它做的就是在我写下帮助"这个词时显示一个警告框,如果输入了其他内容,则说其他内容.

function prompter() {var reply = prompt("这个脚本是为了帮助你了解新乐队,要查看更多信息,请输入帮助,否则,只需单击确定")if (回复 === 'help' || 'Help'){alert("这个脚本可以帮助你找到新的乐队.它最初是用 Python 3.0.1 编写的,使用 Komodo IDE,然后手动翻译成 Javascript.请诚实回答问题.如果您对问题没有意见,只需按无需输入任何内容即可.")}别的{alert("按确定继续")}};

但是,无论发生什么,第一个警告框都会弹出,即使您按下取消!我该如何解决这个问题???

解决方案

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

应该是:

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

因为 'Help' 是真实的",所以 if 的第一部分将始终被输入.

当然,最好进行不区分大小写的比较:

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

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

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.

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

but, what happens, is no matter what, the first alert box pops up, even if you press cancel! How should I fix this???

解决方案

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/

这篇关于javascript 中的 if 语句始终为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆