2013-02-19 85 views
0

我有一個檢測碰撞檢測的方法hitTest,並且可以返回一個Point對象(如果發生碰撞)或(如果沒有碰撞),它返回nullundefined (我還沒有深刻理解它何時返回null或未定義,但我相信Chrome控制檯)。檢查兩個對象是否都是未定義的或在javascript中爲空

我必須測試2個對象的碰撞。並檢查一個或兩個碰撞是否發生。我曾嘗試這樣的代碼:

var result1 = hitTest(player, object1); 
var result2 = hitTest(player, object2); 
if(result1 || result2) { blabla() }; 

,但它不工作。

現在..我知道,js是一個棘手的語言,我想一個聰明的方式來做到這一點,而不寫typeof 4次。我在想蟒蛇短路邏輯運算符...

+0

'||'返回第一個找到的'true',如果找不到'true',則返回'false'。 '&&'返回第一個找到的'false',如果不是'false'則返回'true'。 – Teemu 2013-02-19 19:17:12

+0

謝謝。添加它作爲答案,我可以使用它作爲正確的答案 – nkint 2013-02-19 19:22:06

+0

如果有(0,至少1,2)碰撞你想要你的if語句爲真嗎? – 2013-02-19 19:32:13

回答

2

您可以使用&&,它返回第一個檢測false/null/undefined/0,即if不會通過,如果任一result1result2null

+1

更好的方式來說這是: 對於'&&'要通過,BOTH必須是'true'。對於'||'來說,只有一個必須是'true'。 – krillgar 2013-02-19 19:28:44

+0

@krillgar是的,如果我們在談論「if」。我正在談論'&&'操作符,它真的返回其任一操作數。雖然固定的答案,因爲「如果」本身並沒有失敗...... – Teemu 2013-02-19 20:12:41

1

您不需要的那些無論如何已經4次寫typeof;

強制範式條件語句和運營商:

//TYPE   //RESULT 
Undefined  // false 
Null    // false 
Boolean   // The result equals the input argument (no conversion). 
Number   // The result is false if the argument is +0, −0, or NaN; otherwise the result is true. 
String   // The result is false if the argument is the empty String (its length is zero); otherwise the result is true. 
Object   // true 

從Mozilla的:

邏輯與(&&

表達式1 & &表達式2
如果第一個操作數(expr1)可以轉換爲false,則&&操作員將返回false而不是expr1的值。

邏輯OR(||

expr1的|| expr2 返回expr1如果它可以轉換爲true;否則,返回expr2。因此,如果使用布爾值,則||返回true,如果任一操作數是true;如果兩者都是false,則返回false

true || false // returns true 
true || true // returns true 
false || true // returns true 
false || false // returns false 
"Cat" || "Dog"  // returns Cat 
false || "Cat"  // returns Cat 
"Cat" || false  // returns Cat 

true && false // returns false 
true && true // returns true 
false && true // returns false 
false && false // returns false 
"Cat" && "Dog" // returns Dog 
false && "Cat" // returns false 
"Cat" && false // returns false 

此外,您可以使用快捷isset()方法就像在PHP正確驗證您的對象:

function isSet(value) { 
    return typeof(value) !== 'undefined' && value != null; 
} 

左右;您的代碼是:

var result1 = hitTest(player, object1), 
    result2 = hitTest(player, object2); 
if (isSet(result1) && isSet(result2)) { blabla(); }; 
相關問題