gpt4 book ai didi

javascript - [] 与 [] 不同

转载 作者:行者123 更新时间:2023-12-03 02:29:57 26 4
gpt4 key购买 nike

我被要求用 Javascript 编写一个函数 sortByFoo 来正确响应此测试:

// Does not crash on an empty array
console.log(sortByFoo([]) === []);

但我尝试过一些事情:

[] === [];
>> false

所以我可以确定,无论 sortByFoo 函数如何,这样的测试总是会失败,不是吗?但我想解释为什么会发生这种情况。为什么 [] 不等于/等于 [] ?

请原谅我的近似英语,这不是我的母语:p

最佳答案

如果您查看 javascript/ecmascript 的规范,特别是 section 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
    • 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.

由于您的数组一直到第七步,因此它们必须是同一个对象,而不仅仅是两个相同的对象。常规相等运算符 (==) 也是如此。

关于javascript - [] 与 [] 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473961/

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