Why does 1==1==1 return true, "1"=="1"=="1" return true, and "a"=="a"=="a" return false?

function a() { return (1 == 1 == 1); }
function b() { return ("1" == "1" == "1"); }
function c() { return ("a" == "a" == "a"); }

I tested the above code in Chrome's console and for some reason, a() returns true, b() returns true, and c() returns false.

Why is this so?

9819 次浏览

因为 1 == true

但是 "a" != true

所以基本上就是

1 == 1"1" == "1""a" == "a"都被评估为 true,然后与下一个值进行比较。

字符串 "1"在与 true比较之前被转换为一个数字(1) ,因此也被认为等于 true

现在,“为什么? ! ? !”这个问题的解释是 Javascript 起源于 C 语言家族。其中除0以外的任何数字都被认为是有效的 true布尔值。:-/

因为您正在将第一个等式的(布尔)结果与第三个(非布尔)值进行比较。

在代码中,1 == 1 == 1等价于 (1 == 1) == 1等价于 true == 1

This means the three methods can be written more simply as:

function a() { return (true == 1); }
function b() { return (true == "1"); }
function c() { return (true == "a"); }

这些比较是根据 这些规则(重点是我的)进行的:

如果两个操作数不属于同一类型,则 JavaScript 将 然后应用严格的比较。如果任何一个操作数是 如果是数字或布尔值,则操作数将转换为数字 可能 ; 否则,如果任何一个操作数是字符串,则字符串操作数为 如果可能,转换为数字。如果两个操作数都是对象,则 JavaScript 比较操作数时相等的内部引用 引用内存中的同一对象。

所以在 c中发生的是,"a"被转换成一个数字(给出 NaN) ,结果是 严格比较true被转换成一个数字(给出 1)。

因为 1 === NaNfalse,所以第三个函数返回 false。很容易看出为什么前两个函数将返回 true

因为1和“1”都被转换为真,作为数字。A 不是这样的。因此:

("1" == "1" == "1")

评估为

(("1" == "1") == "1")

计算结果为

(true == "1")

同样地,

("1" == 1 == "1")

实际上,任何非零数在转换为布尔值时都为真。

然而,“ a”不等于真。

这是真的,(1 == 1) == 1。那么它将是 true == 1,但不是在 a == a == a

It's because JavaScript is a weakly typed language. This means that it is not expressive enough to talk about types, and in fact implicitly coerces values to belong in types to which they have no semantic relation. So, (1 == 1) == 1 evaluates to true because (1 == 1) correctly evaluates to true, so that JavaScript evaluates (true) = 1. In particular, it is turning 1 to a boolean (or true to a number -- I forget which, but the result is effectively the same).

重点是,JavaScript 是 转身的一种类型的值转换成另一种类型的值在你的背后。

你的问题显示了为什么这是一个问题: (‘ a’= = ‘ a’) = = ‘ a’是假的,因为(‘ a’= = ‘ a’)是真的,而 JavaScript 最终会比较(true) = = ‘ a’。因为只有 没有合理地将布尔值转换为字母(或字母转换为布尔值) ,所以这种说法是错误的。当然,这打破了(= =)的参照透明度(计算机科学)。

布尔值以位的形式处理,每个位代表真或假(1表示真,0表示假)

so that 1 stands for true, and 0 stand for false

and 1 == 1 == 1 will be like (1 == 1) == 1, true == 1, true

而‘ a’= = ‘ a’= = ‘ a’将是(‘ a’= = ‘ a’) = = ‘ a’,true = = ‘ a’,false

BONUS: 0 == 1 == 0, 1 == 0 == 0 and 0 == 0 == 1 returns true