为什么“” ==" 0"在JavaScript中是假的?
我想在这里了解一些事情,解释自己的最好方法就是给出一个例子:
I am trying to understand something here , best way to explain myself is by giving an example :
"" == false
// true
"0" == false
// true
false == false
// true
但这里会发生什么?
"" == "0"
// false
如果评估为 false 和0评估为 false 逻辑预测它与我写的相同 false == false 。
If "" evaluates to false and "0" evaluates to false the logic predicts that it is the same as i write false == false .
我确实意识到我想在这里比较两个字符串,但语言如何知道a==b之间的区别>或==0?在这种情况下如何发生强制?
i do realize that i am trying to compare two strings here , but how does the language knows the difference between "a" == "b" or "" == "0" ? how does coercion happens in this case ?
为什么==0在javascript中为false?
Why "" == "0" is false in javascript?
因为操作数是两个具有不同内容的字符串。只有当操作数的数据类型不同时才会发生类型强制。
Because the operands are two strings with different content. Type coercion only takes place if the data types of the operands are different.
相关问题:
- Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')
- '\n\t\r' == 0 is true?
如果
评估为false且0评估到false逻辑预测它和我写的一样false == false
If
""evaluates to false and"0"evaluates tofalsethe logic predicts that it is the same as i writefalse == false
让我们看看比较实际是如何解决的:
Lets have a look how the comparisons are actually resolved:
== false 被强制为 0 == 0
0== false 被强制为 0 == 0
false == false :相同的数据类型,因此值直接比较
false == false: same data type, hence the values are directly compared
正如您所见0未评估为 false ,它被转换为整数, 值被比较。 (评估为 false (空字符串)但转换为数字时,它是 0 )。
As you can see "0" doesn't "evaluate" to false, it is converted to an integer, and that value is compared. ("" does evaluate to false (empty string) but when converted to a number, it is 0).
将值转换为布尔值与之间存在很大差异将值与布尔值进行比较。最明显的例子: !!0( true )和0== false ( true )。
There is a big difference between converting a value to a boolean and comparing a value to a boolean. Most obvious example: !!"0" (true) and "0" == false (true).
当您将不同数据类型的值与松散比较进行比较时( == ),它们总是被强制转换为数字(或者可能是字符串,如果您要将对象与字符串进行比较)。
When you compare values of different datatypes with loose comparison (==), they are always coerced to numbers (or potentially strings, if you are comparing an object with a string).
查看规范有关比较算法的更多信息。
Have a look at the specification for more information about the comparison algorithm.