如果 b = [1, 2, 3, 4],并且 c = [...b],为什么 b 不等于 c?

If b = [1, 2, 3, 4], and c = [...b], why doesn't b equal c?

标题几乎已经说明了一切,但在这里写出来:

b = [1, 2, 3, 4];
c = [...b];

b === c; //false

为什么?

c 是一个新的 Array 实例,不是同一个对象。

您可以使用 .every() 检查索引 b 处的每个元素是否与索引 c

处的元素具有相同的值
let bool = b.every((n, index) => c[index] === n)

这就是常规数组 identity / strict equality comparison 的工作原理。请记住,数组是对象:

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
    • If x is NaN, return false.
    • If y is NaN, return false.
    • If x is the same Number value as y, return true.
    • If x is +0 and y is −0, return true.
    • If x is −0 and y is +0, return true.
    • 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.

NOTE This algorithm differs from the SameValue Algorithm (9.12) in its treatment of signed zeroes and NaNs.

...没有影响。如果我们为两者分配相同的文字,我们可以看到:

b = [1, 2, 3, 4];
c = [1, 2, 3, 4];

b === c; //false

这是因为每个 [] 都会创建一个新数组,即使它在其中使用了一个 spread。