gpt4 book ai didi

JavaScript:为什么是 []==![]?

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:48 26 4
gpt4 key购买 nike

在 JavaScript 中,我注意到 []==![] 结果是 truedemo

我不明白这个结果。你能解释一下为什么吗?

最佳答案

[] 是一个数组,但是 ![] 是一个 bool 值。每当您尝试使用 == 比较两个不同类型的对象时,这两个对象都应转换为可比较的对象(使用 ToNumber,请参见 11.9.3 中的步骤 7)。这就是为什么 [] == ![] 产生 true,第一个空数组被评估为 false

11.9.3 The Abstract Equality Comparison Algorithm

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. [...]
  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 or Number 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 or Number, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

但是,如果您使用严格类型比较运算符 ===,则结果为 false,因为两种类型不同:

11.9.6 The Strict Equality Comparison Algorithm

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 different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is Number, then
    1. If x is NaN, return false.
    2. If y is NaN, return false.
    3. If x is the same Number value as y, return true.
    4. If x is +0 and y is -0, return true.
    5. If x is -0 and y is +0, return true.
    6. Return false.
  5. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  7. Return true if x and y refer to the same object. Otherwise, return false.

关于JavaScript:为什么是 []==![]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12871263/

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