它们根本不相等。
if (x)
检查x 是否为Truthy,后者检查x 的布尔值是否为true。
例如,
var x = {};
if (x) {
console.log("Truthy");
}
if (x == true) {
console.log("Equal to true");
}
不仅是一个对象,任何字符串(空字符串除外),任何数字(0 除外(因为0 是 Falsy)和1)都会被认为是真值,但它们不会等于真的。
根据ECMA 5.1 Standards,在if (x)中,x的真实性将根据下表来确定
+-----------------------------------------------------------------------+
| Argument 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 |
+-----------------------------------------------------------------------+
注意:最后一行object,包括对象和数组。
但在后一种情况下,按照The Abstract Equality Comparison Algorithm,
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
x 的值将被转换为一个数字,并且该数字将与 true 进行核对。
注意:
在 JavaScript 中,true 是 1,false 是 0。
console.log(1 == true);
# true
console.log(0 == false);
# true