In the Google JavaScript style guide, it says not to use wrapper objects for primitive types. It says it's "dangerous" to do so. To prove its point, it uses the example:
var x = new Boolean(false);
if (x) {
alert('hi'); // Shows 'hi'.
}
OK, I give up. Why is the if code being executed here?
因为每个变量, typeof
Object
是truthy和包装都是对象。
if(x)
will run if x
is truthy.
x
is truthy if it's not falsey.
x is falsey if x is null
, undefined
, 0
, ""
, false
So since new Boolean(false)
is an Object
and an Object
is truthy, the block runs
In the if(x)
case, it's actually evaluating the default Boolean of the object named and not its value of false
.
So be careful using Boolean
objects instead of Boolean
values. =)
The following code uses a Boolean object. The Boolean object is false, yet console.log("Found")
still executes because an object is always considered true inside a conditional statement. It doesn't matter that the object represents false; it's an object, so it evaluates to true.
var found = new Boolean(false);
if (found)
{ console.log("Found");
// this executes
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.