进行三重比较时会发生什么? (Javascript)
What happens when doing triple comparison? (Javascript)
首先:我知道这不是应该如何进行比较,这只是一个兴趣问题。
假设您进行此比较:
var x = 0;
if(1 < x < 3) {
console.log("true");
} else {
console.log("false");
}
那个 if 语句内部发生了什么,所以输出是 "true"?
是否发生了一些隐含的逻辑比较。我怎么知道?
比较从左到右进行,因此 1 < x < 3
的计算结果为
1 < x
首先是 false
,因为 x
是 0
。下一个比较是,
false < 3
将是 true
,因为将 false
隐式类型转换为数字表示形式,即 0
。因此,表达式的计算结果为 0 < 3
,即 true
。
因此,当您执行 true < 3
或 false < 3
时,此布尔值将隐式转换为 0
作为 false
和 1
作为 true
.
根据ECMAScript® 2018 Language Specification,(7.2.14)这种比较方式如下:
7.2.14 Abstract Equality Comparison
If Type(x) is the same as Type(y), then
Return the result of performing Strict Equality Comparison x === y.
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
If Type(x) is Number and Type(y) is String, return the result of the
comparison x == ! ToNumber(y).
If Type(x) is String and Type(y) is Number, return the result of the
comparison ! ToNumber(x) == y.
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).
If Type(x) is either String, Number, or Symbol and Type(y) is Object,
return the result of the comparison x == ToPrimitive(y).
If Type(x) is Object and Type(y) is either String, Number, or Symbol,
return the result of the comparison ToPrimitive(x) == y.
Return false.
并且:
7.1.3 ToNumber ( argument ): If argument is true, return 1. If argument is false, return +0.
(粗体是我的)
所以:
(1 < 0 ) < 3
false < 3
0 < 3
true
首先:我知道这不是应该如何进行比较,这只是一个兴趣问题。 假设您进行此比较:
var x = 0;
if(1 < x < 3) {
console.log("true");
} else {
console.log("false");
}
那个 if 语句内部发生了什么,所以输出是 "true"? 是否发生了一些隐含的逻辑比较。我怎么知道?
比较从左到右进行,因此 1 < x < 3
的计算结果为
1 < x
首先是 false
,因为 x
是 0
。下一个比较是,
false < 3
将是 true
,因为将 false
隐式类型转换为数字表示形式,即 0
。因此,表达式的计算结果为 0 < 3
,即 true
。
因此,当您执行 true < 3
或 false < 3
时,此布尔值将隐式转换为 0
作为 false
和 1
作为 true
.
根据ECMAScript® 2018 Language Specification,(7.2.14)这种比较方式如下:
7.2.14 Abstract Equality Comparison If Type(x) is the same as Type(y), then
Return the result of performing Strict Equality Comparison x === y.
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
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).
If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
Return false.
并且:
7.1.3 ToNumber ( argument ): If argument is true, return 1. If argument is false, return +0.
(粗体是我的)
所以:
(1 < 0 ) < 3
false < 3
0 < 3
true