gpt4 book ai didi

javascript - JavaScript 在与 == 进行比较时如何转换类型?

转载 作者:行者123 更新时间:2023-11-28 12:07:46 26 4
gpt4 key购买 nike

alert (0 == ''); // true
alert (0 == '0'); // true

JSFiddle Proof

我知道 JavaScript 中的 == 会执行转换,然后检查是否相等,但是上面语句中的 == 是如何执行转换的呢?它将 0 转换为 '' 还是 '' 转换为 0?或者也许还有别的什么?是否有规范可以解释其实现?

最佳答案

它使用 Abstract Equality Comparison Algorithm .

专门针对您的示例

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

那么你最终会得到:

0 == 0

...在这两种情况下,因为空字符串会转换为数字 0,而数字字符串会转换为给定的数字。

来自9.3.1 ToNumber Applied to the String Type :

A StringNumericLiteral that is empty or contains only white space is converted to +0

由于我们现在在第二遍中对相同类型进行比较,因此它将执行以下操作:

If Type(x) is the same as Type(y), then

... If Type(x) is Number, then

... If x is the same Number value as y, return true.

<小时/>

要测试 toNumber 转换,您可以使用一元 + 运算符。

console.log( +'' );   // 0
console.log( +'0' ); // 0

关于javascript - JavaScript 在与 == 进行比较时如何转换类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7363961/

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