!!1=="1" 等于 True 和 > !!2=="2" 等于: False 同样,为什么 > "1"==true 等于 true 而 > "2"==true 等于 fal-6ren">
gpt4 book ai didi

javascript - 为什么 !!1= ="1"等于 true 而 !!2= ="2"等于 false?

转载 作者:IT王子 更新时间:2023-10-29 02:51:51 24 4
gpt4 key购买 nike

如标题所述,为什么:

> !!1=="1"

等于

True

> !!2=="2"

等于:

False

同样,为什么 > "1"==true 等于 true> "2"==true 等于 false

我很困惑。这些只是 JS 中的错误还是这里发生了什么?

最佳答案

根据 Operator precedence规则,逻辑 !== 具有更高的优先级。因此,在这两种情况下,首先评估 !!

注意:this answer中已经解释了各种对象的真实性。我的。

第一个案例

!!1 == "1"

!1 将被评估为 false,因为 1 被认为是 Truthy。再次否定我们得到 true。所以表达式变成了

true == "1"

现在,当您使用 == 运算符时,强制规则开始生效,该运算符根据 The Abstract Equality Comparison Algorithm 进行评估在 ECMAScript 5.1 规范中定义,

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

因此,true 将被转换为一个数字,根据 ToNumber algorithm for Boolean values 为 1 .现在表达式变成了

1 == "1"

现在,

4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

因此,"1" 将被转换为一个数字,并根据 ToNumber algorithm 给出 1 .这就是为什么它在第一种情况下显示 true 的原因。

第二种情况

此处应用相同的规则。

!!2 == "2"

成为

true == "2"

然后

1 == "2"

变成

1 == 2

这不是 true,这就是第二种情况打印 false 的原因。

关于javascript - 为什么 !!1= ="1"等于 true 而 !!2= ="2"等于 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23693089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com