gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:20 24 4
gpt4 key购买 nike

我有以下代码片段:

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/

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