我被要求用 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:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- 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.
- 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.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false.
由于您的数组一直到第七步,因此它们必须是同一个对象,而不仅仅是两个相同的对象。常规相等运算符 (==
) 也是如此。
关于javascript - [] 与 [] 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473961/