你不需要写typeof4 次,但无论如何;
条件语句和运算符的强制范式:
//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:
逻辑与 ( &&)
expr1 && expr2
如果第一个操作数 ( expr1) 可以转换为false,则&&运算符返回false而不是 的值expr1。
逻辑或 ( ||)
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(); };