Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here is a javascript comparison:

(这是一个JavaScript比较:)

2 == true //false

it's said, the reason why return false, is because the comparison convert the true to Number datatype, and result is 1:

(据说返回false的原因是因为比较将true转换为Number数据类型,结果为1:)

console.info(Number(true)) // 1

My confuse is, why the comparison don't convert the number 2 to Boolean datatype

(我的困惑是,为什么比较不将数字2转换为Boolean数据类型)

console.info(Boolean(2)) // true

and the 2 == true result could be true ?

(和2 == true结果可能是true吗?)

  ask by hh54188 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
467 views
Welcome To Ask or Share your Answers For Others

1 Answer

I find the doc here:

(我在这里找到文档:)

Comparison Operators , which said:

(比较运算符 ,表示:)

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison.

(如果两个操作数的类型不同,则JavaScript会转换操作数,然后进行严格比较。)

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 other operand is converted to a string if possible.

(否则,如果其中一个操作数是一个字符串,则另一个操作数将尽可能转换为字符串。)

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

(如果两个操作数都是对象,则JavaScript将比较内部引用,当操作数引用内存中的同一对象时,内部引用相等。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...