javascript - 字符串强制转换为 bool 值

标签 javascript coercion

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:

  1. If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. 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/

相关文章:

iphone - 在 ARM 与 Intel 上将 float 强制转换为 unsigned char

php - 删除 submit.x 和 submit.y 但保留 URL 中的其他值

javascript - 使用 Grunt + Git 为 JavaScript 项目构建增量更新的工作流程

java - Tapestry - 枚举强制

raku - Perl6 中的类型强制

Python:如何对 re 的匹配字符串进行操作

r - 强制 HCPC 对象到 hclust 以使用库(ape)

javascript - 包装器中的中心表格

javascript - 如何在Threejs中从平面发出光?

javascript - 我应该忽略 React 警告 : Input elements should not switch from uncontrolled to controlled?