为什么 [null, undefined, []] == ",," 返回 true

Raj*_*jat 0 javascript arrays coercion comparison-operators

我知道抽象比较会将 LHS 转换为 StringString([null, undefined, []])并将结果为',,'.

但是String(null)'null'并且String(undefined)'undefined'。因此,如何String([null, undefined, []])',,'

zer*_*kms 6

那是因为。

  1. 这就是如何==定义https://tc39.es/ecma262/#sec-abstract-equality-comparison参见步骤 11:If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return the result of the comparison ? ToPrimitive(x) == y.
  2. 然后ToPrimitive发生:https : //tc39.es/ecma262/#sec-toprimitive
  3. 然后OrdinaryToPrimitive发生:https://tc39.es/ecma262/#sec-ordinarytoprimitive调用Array.prototype.toString
  4. 对于它调用的数组,Array.prototype.join(arr)请参阅https://tc39.es/ecma262/#sec-array.prototype.tostring
  5. Array.prototype.join就是实现的方式:https : //tc39.es/ecma262/#sec-array.prototype.join,最重要的步骤:
Repeat, while k < len,

* If k > 0, set R to the string-concatenation of R and sep.
* Let element be ? Get(O, ! ToString(k)).
* If element is undefined or null, let next be the empty String; otherwise, let next be ? ToString(element).
* Set R to the string-concatenation of R and next.
* Set k to k + 1.
Run Code Online (Sandbox Code Playgroud)