[英]Javascript comparisons
I would like to know why the following comparisons in javascript will give me different results. 我想知道为什么下面的javascript比较会给我不同的结果。
(1==true==1)
true
(2==true==2)
false
(0==false==0)
false
(0==false)
true
I can not figure out why. 我不知道为什么。
The tests are equivalent to these: 测试等效于以下这些:
(true==1)
true
(false==2)
false
(true==0)
false
which is equivalent to these: 等效于这些:
(1==1)
true
(0==2)
false
(1==0)
false
In each case the ==
converts the boolean to a number 1
or 0
. 在每种情况下,
==
将布尔值转换为数字1
或0
。 So the first ==
in each one gives the initial true/false
value, which is then used as the first operand for the second ==
. 因此,每个
==
中的第一个==
给出初始的true/false
值,然后将其用作第二个==
的第一个操作数。
Or to put it all inline: 或全部内联:
((1==true)==1)
((1==1) ==1)
((true) ==1)
((1) ==1)
true
((2==true)==2)
((2==1) ==2)
((false) ==2)
((0) ==2)
false
((0==false)==0)
((0==0) ==0)
((false) ==0)
((0) ==0)
false
I think this is because it is parsed as such: 我认为这是因为它是这样解析的:
( (0 == false) == 0 )
Which would be saying 哪个会说
( true == false )
Each of this operation is done in two steps. 每个操作都分两个步骤完成。
(1==true==1)
first operation is 1 == true => true 第一个操作是1 == true => true
So second is true == 1 => true 所以秒是真的== 1 =>是
(2==true==2)
first operation is 2 == true => false (just number 1 is equivalent to true in js) 第一个操作是2 == true => false(只是数字1等效于js中的true)
So second is false == 2 => true 所以第二个是假== 2 =>是
(0==false==0)
first operation is 0 == false => true 第一个操作是0 ==假=>真
So second is true == 0 => false 所以第二个是true == 0 => false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.