Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript的IF语句中使用具有布尔值的变量作为条件?_Javascript_If Statement_Boolean - Fatal编程技术网

如何在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

如何在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 (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)