JS类型强制如何工作? [英] How does JS type coercion work?

查看:147
本文介绍了JS类型强制如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 == === 并遇到此answer 对理解这个概念非常有帮助。但是我想知道其中一个例子:

I'm learning about == vs. === and came across this answer which was very helpful in understanding the concept. However I wondered about one of the examples:

'0' == false     // true

这可能有意义,因为 == 不会检查类型。但后来我在控制台中尝试了一些可能的强制措施,发现了以下内容:

This might make sense, since == doesn't check for type. But then I tried some possible coercions in the console and found the following:

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

我原以为 '0'== false 具有与'0'=== String(false)相同的真值,但似乎没有是这样的。

I would have thought '0' == false has the same truth value as '0' === String(false), but that doesn't seem to be the case.

那么强制如何实际起作用?是否有一种我缺少的基本类型?

So how does the coercion actually work? Is there a more basic type I'm missing?

推荐答案

0是包含字符 0 的字符串,数字值 0 。评估为 false 的唯一字符串类型值为

"0" is a string containing the character 0, it is not the numeric value 0. The only string-type value which evaluates to false is "".

0 truthy

ECMAScript 262规范的第9.2节定义了不同类型如何转换为布尔值:

Section 9.2 of the ECMAScript 262 specification defines how different types are converted to Boolean:

Argument Type   Result
Undefined       false
Null            false
Boolean         The result equals the input argument (no conversion).
Number          The result is false if the argument is +0, −0, or NaN; otherwise the
                result is true.
String          The result is false if the argument is the empty String (its length is
                zero); otherwise the result is true.
Object          true

然而,只有在使用<$ c $进行比较时才会严格遵循c> === 。

当使用布尔值('0')时你'将值'0'转换为布尔值(与使用 !!'0'相同)。当松散地比较'0' false 时,布尔值将转换为数字(如定义的这里)。 false ,当转换为数字时,变为 0 。这意味着最终计算是'0'== 0 ,相当于 true

When using Boolean('0') you're converting the value '0' to Boolean (which is the same as using !!'0'). When loosely comparing '0' with false, the Boolean value is converted to a number (as defined here). false, when converted to a number, becomes 0. This means the final calculation is '0' == 0 which equates to true.

总结上述ECMAScript规范链接部分的相关部分:

To summarise the relevant part of the linked section of the ECMAScript specification above:


  1. x = '0' y = false

  2. 检查 y 的类型是否为布尔值。

  3. 如果为true,则将 y 转换为数字。

  4. x y 的等效数字进行比较。

  1. Let x = '0' and y = false.
  2. Check if the type of y is Boolean.
  3. If true, convert y to a number.
  4. Compare x to the numeric equivalent of y.

在我们的例子中,JavaScript的实现方式是:

In our case, a JavaScript implementation of this would be:

var x = '0',                      // x = "0"
    y = false;                    // y = false

if (typeof y === "boolean") {
    y = +y;                       // y = 0
}

console.log( x == y );            // "0" == 0



-> true

这篇关于JS类型强制如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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