Boolean("a")
在浏览器控制台中返回 true。
那么为什么
"a" == true
返回错误?
最佳答案
==
运算符如何在某些类型上发挥作用在 ECMAScript specifications 中定义。 。如下:
7.2.13 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
- If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
- If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
- If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
- If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
- If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
- If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
- Return false.
现在我们可以将它们应用到上面的案例中。首先将 bool 值转换为数字,然后尝试将字符串转换为数字(被解析为 NaN):
"a" == true
// Case 7 (true --> 1)
// =>"a" == 1
// Case 5 ("a" --> NaN)
// => NaN == 1
=> false
关于javascript - 字符串强制转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45592586/