Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

javascript - Javascript:关于比较“ 2 == true”的困惑(Javascript: the confuse about comparison “2 == true”)

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

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

1 Reply

0 votes
by (71.8m points)

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将比较内部引用,当操作数引用内存中的同一对象时,内部引用相等。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...