在 JavaScript 中,以下哪些情况下以下语句不会逻辑上相等?
if(x){}
并且
if(x==true){}
谢谢
在 JavaScript 中,以下哪些情况下以下语句不会逻辑上相等?
if(x){}
并且
if(x==true){}
谢谢
它们并不完全相等。
if (x)
检查x
的真值性,而后者检查x
的布尔值是否为true
。
例如:
var x = {};
if (x) {
console.log("Truthy");
}
if (x == true) {
console.log("Equal to true");
}
除了空字符串和数字0 (因为0是假值) 以及数字1之外,任何字符串(非空)或数字都会被视为真值,但它们不等于true。
根据ECMA 5.1标准,在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
包括对象和数组。
但在后一种情况下,根据抽象相等比较算法,
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
在第一种形式中,有几种情况会评估为false,例如空字符串、0、未定义、null。
如果你想更语义化一些,可以在表达式前面加上双感叹号:
if(!!x){...}
这将把表达式结果转换为表示相同语义的真值。这更接近于您描述的表达式(x == true)
还要注意,==
是带有类型强制转换的值比较,例如"3" == 3
,而===
也断言相等的类型。
因此它们不是相同的,但通常在逻辑上表示相同的测试,由于语言的语义和您可以使用的!!
x = 'test'
作为示例。 - VisioNx=' '
,x=[]
,x='\n'
,x='false'
- nderscore