为什么以下 javascript 语句的计算结果为真?

Why the following javascript statement evaluates to true?

为什么以下 if 语句的计算结果为 true,因为值为 false?

var x = new Boolean(false);
if (x) {
  // this code is executed
}

来自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

它不会计算为 false,因为它是一个对象。 x 的值是构造函数产生的对象:

Boolean {[[PrimitiveValue]]: false}

对象总是真实的。而是尝试从您构造的对象中获取实际值:

if(x.valueOf()){}

希望对您有所帮助

因为x变成了一个对象,是一个truthy value(即不是false)。

尝试:

var x = false;
if (x) {
  // this code will not be executed 
} else {
  // this code will be executed instead
}

小心你的类型 ;)