2012-01-09 30 views
2

如何在JavaScript中的IF語句中將具有布爾值的變量用作條件?如何在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

如果(信息搜索結果) – 2012-01-09 19:42:36

+0

你可以只使用變量作爲「條件」:'如果(信息搜索結果)',使用一個=不會起作用,因爲=運算符是分配在Java和JScript,如果你想使用這種語法,你應該使用'if(searchResult == true)' – jere 2012-01-09 19:43:09

回答

2
if (searchResult == true) { 
... 
} 

這是一個測試。

短版:

if (searchResult) { 
... 
} 
3

只需直接使用值和Javascript將決定它是否truthy與否。

if (searchResult) { 
    // It's truthy 
    ... 
} 

原始樣本中的問題是您正在使用searchResult = true。這不是一個簡單的條件檢查,而是一個賦值,它會導致一個值被檢查爲條件值。這是大致的說出以下

searchResult = true; 
if (true) { 
    ... 
} 

在JavaScript中=操作員可以通過多種方式

  • =這被用於用於分配
  • ==這是用於等效強制平等檢查
  • ===這是用於嚴格的平等檢查
+0

這裏較大的一點是,他的代碼不工作的原因是因爲他使用'='將'true'分配給'searchResult '而不是使用'=='來比較它們。 – 2012-01-09 19:44:46

+0

@JustinSatyr更新的答案更完整 – JaredPar 2012-01-09 19:47:05

+0

而且'if'而不是'if'。 – 2012-01-09 19:47:24

1
if (searchResult) is the same as if(searchResult == true) 
if (!searchResult) is the same as if(searchResult == false)