<分区>
function a() { return (1 == 1 == 1); }
function b() { return ("1" == "1" == "1"); }
function c() { return ("a" == "a" == "a"); }
我在 Chrome 的控制台中测试了上面的代码,出于某种原因,a()
返回 true,b()
返回 true,而 c()
返回 false。
为什么会这样?
标签 javascript
<分区>
function a() { return (1 == 1 == 1); }
function b() { return ("1" == "1" == "1"); }
function c() { return ("a" == "a" == "a"); }
我在 Chrome 的控制台中测试了上面的代码,出于某种原因,a()
返回 true,b()
返回 true,而 c()
返回 false。
为什么会这样?
最佳答案
因为您正在比较第一个相等的( bool )结果与(非 bool )第三个值。
在代码中,1 == 1 == 1
等价于(1 == 1) == 1
等价于true == 1
.
这意味着这三个方法可以更简单地写成:
function a() { return (true == 1); }
function b() { return (true == "1"); }
function c() { return (true == "a"); }
这些比较根据 these rules 进行(强调我的):
If the two operands are not of the same type, JavaScript converts the operands, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
那么 c
中发生的事情是 "a"
被转换为数字(给出 NaN
),结果是 strictly compared到 true
转换为数字(给出 1
)。
因为 1 === NaN
是 false
,所以第三个函数返回 false
。很容易看出为什么前两个函数将返回 true
。
关于javascript - 为什么1==1==1返回true, "1"= ="1"= ="1"返回true, "a"= ="a"= ="a"返回false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561542/