您不需要的那些无论如何已经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