[] is not identical to [] [duplicate]

我是研究僧i 提交于 2019-12-02 02:35:39

If you look at the specification for javascript/ecmascript, particularly section 11.9.6, you will see how comparisons with === are performed.

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.

Since your arrays go all the way down to the seventh step they will have to be the same object, not just two identical objects. The same goes for the regular equality operator (==).

Because every time you write [] you are calling array's constructor.

[] is the same as new Array(), and in Javascript new objects compared with equals method are different. See the reference, it is the same as new Object() when using {}.

Italo Borssatto

When you do [] === [] you're comparing references and not values (or deep comparison by values).

Take a look at this solution for javascript array comparison: Comparing two arrays in Javascript

Yes, you are correct that two array literals are never equal. That's because they are references to two separate instances of arrays.

The code to describe the test should be written:

var arr = [];
var result = sortByFoo(arr);
console.log(result === arr && result.length == 0);

Checking that the reference returned by the function is the same that was sent in, and that the array is still empty, ensures that the function returned the same array unchanged.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!