为什么“” ==" 0"在JavaScript中是假的? [英] Why "" == "0" is false in javascript?

查看:107
本文介绍了为什么“” ==" 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 to false the logic predicts that it is the same as i write false == 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.

这篇关于为什么“” ==" 0"在JavaScript中是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆