如何在JavaScript的IF语句中使用具有布尔值的变量作为条件?
如何在JavaScript的IF语句中使用具有布尔值的变量作为条件如何在JavaScript的IF语句中使用具有布尔值的变量作为条件?,javascript,if-statement,boolean,Javascript,If Statement,Boolean,如何在JavaScript的IF语句中使用具有布尔值的变量作为条件 patt1 = new RegExp ("time"); var searchResult = (patt1.test("what time is it" )); // search for the word time in the string // and return true or false If (searchRes
patt1 = new RegExp ("time");
var searchResult = (patt1.test("what time is it" )); // search for the word time in the string
// and return true or false
If (searchResult = true) // what is the right syntax for the condition?
{
document.write("Word is in the statement");
document.write("<br />");
}
patt1=新的RegExp(“时间”);
var searchResult=(patt1.test(“现在几点”);//在字符串中搜索单词time
//并返回真或假
If(searchResult=true)//条件的正确语法是什么?
{
文件。书写(“声明中有文字”);
文件。写(“
”);
}
这是一个测试
简短版本:
if (searchResult) {
...
}
只需直接使用该值,Javascript就会确定它是否真实
if (searchResult) {
// It's truthy
...
}
原始示例中的问题是您使用的是searchResult=true
。这不是一个简单的条件检查,而是一个赋值,其结果是一个值,然后将该值作为条件检查。这大致相当于说:
searchResult = true;
if (true) {
...
}
在Javascript中,=
操作符可以以多种方式使用
这用于分配=
这用于使用强制进行相等性检查=
这用于严格的相等性检查=
if(searchResult)
,使用one=将不起作用,因为=运算符用于java和jscript中的赋值,如果要使用该语法,应使用if(searchResult==true)
这里更重要的一点是,他的代码不起作用的原因是因为他使用=
将true
分配给搜索结果
,而不是使用=
@JustinSatyr更新的答案来比较它们,以使答案更为完整,并且使用If
而不是If
。谢谢大家的帮助,我刚刚开始编码,我想我仍然犯一些基本的错误。
searchResult = true;
if (true) {
...
}
if (searchResult) is the same as if(searchResult == true)
if (!searchResult) is the same as if(searchResult == false)