Maison  >  Questions et réponses  >  le corps du texte

javascript - 请教JS中的数据类型问题

代码很简单,先看这段

'0' == false;    // true
0 == false;      // true

再来看这段

'0' && console.log('打印出来了~');    // output:打印出来了~
0 && console.log('打印出来了~');      // output:undefined

按道理说,都等同于false,那么为何字符串:'0'的情况下能打印数据呢?

PHP中文网PHP中文网2749 Il y a quelques jours309

répondre à tous(1)je répondrai

  • 天蓬老师

    天蓬老师2017-04-10 14:48:02

    试一下把值 explicit 地转换为 Boolean,我们可以发现以下的结果:

    Boolean('0') // true
    Boolean(0) // false
    

    由此可知,题主贴出的第二段代码是完全可以解释的。至于为什么会有这样的转换结果,参见标准第 9.2 节 对 StringBoolean 的转换的规定:

    The result is false if the argument is the empty String (its length is zero); otherwise the result is true.

    那么机智的题主要问了,第一段代码为何会说 '0' == falsetrue 呢?

    这就要参考标准 11.9.3.7 对 == 的规定(此处 x 指代 == 左侧,y 指代右侧):

    If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

    répondre
    0
  • Annulerrépondre