javascript - 如果一个数组在 JavaScript 中是真值,为什么它不等于真值?

标签 javascript arrays comparison javascript-objects

我有以下代码片段:

if([]) {
  console.log("first is true");
}

consolefirst is true 这意味着 [] 是真的。现在我想知道为什么会这样:

if([] == true) {
  console.log("second is true");
}

还有这个:

if([] === true) {
  console.log("third is true");
}

不是。如果控制台在第一个片段中记录了 first is true,那意味着 [] 应该是 true,对吗?那么为什么后两次比较会失败呢? Here是 fiddle 。

最佳答案

这是规范。通过 ECMAScript 2015 Language Specification , 任何隐含 coerced into a boolean 的对象是真的;这意味着对象是真实的。在 if 语句中,条件一旦被评估并且如果还不是 bool 值,则被强制转换为 bool 值。因此,做:

if([]) { 
  ... 
}

[] 在强制转换为 bool 值且为真时为真。

另一方面,当您尝试使用抽象比较来比较不同类型的两个值时,==,引擎必须在内部通过算法将值减少为相似类型,并最终它可以比较的整数。在 Section 7.2.12 of the specification在抽象相等比较 x == y 的步骤中,它指出:

7.2.12 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(y) is Boolean, return the result of the comparison x == ToNumber(y).

因此,y 操作数(在本例中为 true)通过 ToNumber 强制转换为 1,因为它是一个 bool 值,并且[] == 1 为假,因为:

  1. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y.

这将使用数组的toString方法将x操作数转换为字符串,对于中的空数组是""这个案例。通过 ToPrimitive 后,将产生:

if("" == 1) {
  ...
}

最后:

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

因此,空字符串 ""ToNumber 为 0,您将得到:

if(0 == 1) {
  ...
}

而 0 不等于 1,因此为假。请记住,仅仅因为某些东西是真实的,并不意味着它等于真实。只需尝试 Symbol() == true({}) == true

最后的比较,===strict comparison , 并且不强制转换任何操作数,如果两个操作数不是同一类型,则返回 false。由于左侧操作数是一个对象(数组)而右侧是一个数字,因此比较结果为 false。

关于javascript - 如果一个数组在 JavaScript 中是真值,为什么它不等于真值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44550071/

相关文章:

arrays - 删除排序数组中最小值的时间复杂度

java - 为什么这没有给出错误?

sql - 当条件为 <> true 时,为什么 PostgreSQL 不返回空值

javascript - http 重定向到特定的 https 链接

javascript - Extjs store.filter 按日期范围

javascript - 使用 d3 javascript 库附加 DOM/SVG 元素会更改变量引用/范围,为什么?

python - pbkdf2 和哈希比较

javascript - JQuery 如何创建它的自定义事件?我可以在 Javascript 中重新创建吗?

javascript - 如何获取数组中5个最小值的索引?

javascript - 根据数组检查用户输入,充当猜测 Javascript