在JavaScript中,为什么" 0 QUOT;等于假,但是当测试'如果'它本身不是假的? [英] In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?
问题描述
以下介绍0
是在Javascript假的:
>>> 0==假
真正>>>假==0
真正
那么,为什么下面的打印哈
?
>>>如果(0)的console.log(医管局)
哈
究其原因是因为当你做明确 ==虚假
,双方都被转换为0以数字和的然后的比较进行的。
当你这样做:如果(0)的console.log(医管局)
,字符串值进行测试。任何非空字符串真正
,而一个空字符串假
。
等于(==)的
如果这两个操作数的不是同一类型的,JavaScript的转换操作数则实行严格的比较。如果一个操作数为一个数字或一个布尔值的操作数转换为如果可能的数字;否则,如果一个操作数为字符串,则另一个操作数转换为字符串,如果可能的。如果两个操作数都是对象,然后比较JavaScript的内部引用时,操作数指的是同一个对象在内存里面都是平等的。
(从<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators\">Comparison在Mozilla开发者网络运营商)
块引用>The following shows that
"0"
is false in Javascript:>>> "0" == false true >>> false == "0" true
So why does the following print
"ha"
?>>> if ("0") console.log("ha") ha
解决方案The reason is because when you explicitly do
"0" == false
, both sides are being converted to numbers, and then the comparison is performed.When you do:
if ("0") console.log("ha")
, the string value is being tested. Any non-empty string istrue
, while an empty string isfalse
.Equal (==)
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.
(From Comparison Operators in Mozilla Developer Network)
这篇关于在JavaScript中,为什么&QUOT; 0 QUOT;等于假,但是当测试'如果'它本身不是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!