Javascript:关于比较的混淆“2 == true” [英] Javascript: the confuse about comparison "2 == true"
问题描述
以下是javascript比较:
Here is a javascript comparison:
2 == true //false
据说,返回false的原因是因为比较将 true
转换为数字
数据类型,结果为1:
it's said, the reason why return false, is because the comparison convert the true
to Number
datatype, and result is 1:
console.info(Number(true)) // 1
我的混淆是,为什么比较不转换数字 2
到布尔值
数据类型
My confuse is, why the comparison don't convert the number 2
to Boolean
datatype
console.info(Boolean(2)) // true
和 2 == true
结果可能是 true
?
推荐答案
我在这里找到了doc:
I find the doc here:
比较运算符,表示:
如果两个操作数不是相同的类型,JavaScript转换
操作数n适用严格的比较。如果任一操作数是数字
或布尔值,则操作数将转换为数字(如果可能); else
如果任一操作数是字符串,则另一个操作数转换为
字符串(如果可能)。如果两个操作数都是对象,则JavaScript
比较内部引用,当操作数引用
时内存中的相同对象时,内部引用相等。
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 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:关于比较的混淆“2 == true”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!