在JavaScript中,为什么"0"等于false,但是当'if'测试时它本身并不是假的?

nop*_*ole 224 javascript boolean

以下显示"0"在Javascript 中为false:

>>> "0" == false
true

>>> false == "0"
true
Run Code Online (Sandbox Code Playgroud)

那么为什么以下打印"ha"

>>> if ("0") console.log("ha")
ha
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 339

显示问题的表:

如果声明的话

和== javascript中所有对象类型的真实比较

故事的道德使用=== 严格平等表现出理智

表生成信用:https://github.com/dorey/JavaScript-Equality-Table

  • 这些表有一个错误.对于`[]`,`{}`,`[[]]`,`[0]`和`[1]`值,`==`或`===`运算符都不计算为真.我的意思是`[] == []`和`[] === []`也是假的. (4认同)
  • 从现在开始,如果有人说他从不使用严格的比较操作员,我会用这些桌子面对他并让他哭泣.仍不确定我是否掌握了"NaN"的概念.我的意思是,'typeof NaN // number`但是`NaN === NaN // false`,嗯...... (3认同)
  • 我的一个朋友制作了http://f.cl.ly/items/3b0q1n0o1m142P1P340P/javascript_equality.html - 与上面相同的图表,但更容易阅读. (3认同)
  • 使用另一个值的顺序https://gist.github.com/kirilloid/8165660更有意义 (2认同)

jdi*_*jdi 246

原因是当您明确地执行操作时"0" == false,双方都将转换为数字,然后执行比较.

执行:时if ("0") console.log("ha"),正在测试字符串值.任何非空字符串都是true,而空字符串是false.

相等(==)

如果两个操作数的类型不同,则JavaScript转换操作数,然后应用严格比较.如果操作数是数字或布尔值,操作数将尽可能转换为数字; 否则,如果任一操作数是字符串,则另一个操作数将转换为字符串(如果可能).如果两个操作数都是对象,则JavaScript比较内部引用,当操作数引用内存中的同一对象时,这些内部引用相等.

(从比较运算符在Mozilla开发者网络)


Inc*_*ito 36

这是根据规格.

12.5 The if Statement 
.....

2. If ToBoolean(GetValue(exprRef)) is true, then 
a. Return the result of evaluating the first Statement. 
3. Else, 
....

根据规范,ToBoolean是

抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:

该表说明了字符串:

在此输入图像描述

如果参数是空String(其长度为零),则结果为false; 否则结果是真的

现在,解释为什么"0" == false你应该读取等于运算符,它指出它从抽象操作GetValue(lref)中获取其值与右侧相同.

其中将此相关部分描述为:

if IsPropertyReference(V), then 
a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get
be the special [[Get]] internal method defined below. 
b. Return the result of calling the get internal method using base as its this value, and passing 
GetReferencedName(V) for the argument

或者换句话说,字符串具有原始基础,它回调内部get方法并最终看起来为false.

如果要使用GetValue操作来评估事物==,如果要使用ToBoolean,请使用===(也称为"严格"等于运算符)


bob*_*nce 12

它是PHP的字符串"0"是falsy(false-when-used-in-boolean-context).在JavaScript中,所有非空字符串都是真实的.

诀窍是,==对布尔值没有在布尔上下文中进行求值,它会转换为数字,对于通过解析为十进制来完成的字符串.所以你得到Number 0而不是真实的布尔值true.

这是一个非常糟糕的语言设计,这是我们尽量不使用不幸运==算符的原因之一.请===改用.


Tha*_*ava 7

// I usually do this:

x = "0" ;

if (!!+x) console.log('I am true');
else      console.log('I am false');

// Essentially converting string to integer and then boolean.
Run Code Online (Sandbox Code Playgroud)


Jas*_*aro 5

你周围的引号0使它成为一个字符串,它被评估为真。

删除引号,它应该可以工作。

if (0) console.log("ha") 
Run Code Online (Sandbox Code Playgroud)

  • 正确的,不是关于如何“让它工作”,而是问题更像是“为什么它表现得那样?” (2认同)