您不需要的那些無論如何已經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(); };
'||'返回第一個找到的'true',如果找不到'true',則返回'false'。 '&&'返回第一個找到的'false',如果不是'false'則返回'true'。 – Teemu 2013-02-19 19:17:12
謝謝。添加它作爲答案,我可以使用它作爲正確的答案 – nkint 2013-02-19 19:22:06
如果有(0,至少1,2)碰撞你想要你的if語句爲真嗎? – 2013-02-19 19:32:13