如何使用带有布尔值的变量作为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 />");
}
答案 0 :(得分:3)
直接使用该值,Javascript将确定它是否真实。
if (searchResult) {
// It's truthy
...
}
原始示例中的问题是您使用的是searchResult = true
。这不是一个简单的条件检查,而是一个赋值,它产生一个值,然后作为条件检查。它大致相当于说下面的
searchResult = true;
if (true) {
...
}
在Javascript中,=
运算符可以以多种方式使用
=
这用于作业==
这用于使用强制等同性检查===
这用于严格的等式检查答案 1 :(得分:2)
if (searchResult == true) {
...
}
这是一个测试。
简短版本:
if (searchResult) {
...
}
答案 2 :(得分:1)
if (searchResult) is the same as if(searchResult == true)
if (!searchResult) is the same as if(searchResult == false)