javascript - [] 与 [] 不同

标签 javascript arrays empy

我被要求用 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/

相关文章:

javascript - 在这一特定场景中数据被覆盖

javascript - 如何使用 Promise 等待函数内的事件完成然后再次调用该函数?

javascript - jQuery UI Datepicker beforeShowDay 函数未运行

javascript - 使用 ember 的垂直图

php - 如何循环访问关联数组值并将数据放入函数中

ios - NSArray 元素无法匹配 Swift 数组元素类型预期 NSMutableArray 但发现 __NSDictionaryI :

java - 为什么这只返回一个7?