问题
Imagine this simple scenario. I have variable that can be plain JS object with one property, ID, that is a number or obj variable can be null. I have simple test() function that checks if the variable is not null and that it must have valid id property.
var obj = { id: 111 };
function test() {
return (obj && obj.id);
}
I am expecting that this function will always return boolean but in fact it returns undefined if the obj is undefined or value of obj.id if object exists like in case above. Why this function return 111 instead of true.
I am going to rip off hair of my head ... Please illuminate my mind :)
回答1:
When obj
is defined, why does if (obj && obj.id)
return 111
?
The logical AND (
&&
) operator returnsexpr1
if it can be converted tofalse
; otherwise, returnsexpr2
.
MDN: Logical Operators - Description (slightly paraphrased)
expr1
(obj
) cannot be converted to false, therefore it returns expr2
(111
).
Why does it not return true
?
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the
&&
and||
actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
MDN: Logical Operators
Because you are using the logical operator with non-Boolean values, the result will be non-Boolean as well.
回答2:
It's a common misconception. In JS (unlike in e.g. PHP) an expression like x && y
does this:
- execute the expression
x
- if the expression
x
returned true, then execute the expressiony
as well and return it (y
). Otherwise returnx
(which would be falsy in this case e.g.0
,''
,false
,null
,undefined
).
In other words it works more like a ternary expression x ? y : z
.
If you want a boolean, then use !!(x && y)
.
来源:https://stackoverflow.com/questions/53597233/js-object-null-checking-weird-js-problem