Is an empty array not equal to itself in Javascript?

I came across a situation where [] == [] is false in Javascript.

Can someone explain why?

+7
javascript
source share
4 answers

Objects are equal by reference, [] is a new object with a new link, the right hand [] also a completely new object with a new link, therefore they are not equal, as:

 var user1 = new User(); var user2 = new User(); user1 === user2; // Never true 
+8
source share

Since they are not the same object, different objects never match, so the result is false .

+2
source share

See Object ID , because both arrays create a new instance of the array, so comparing two different objects is not equal. Your code is equivalent to:

 var arr1 = [], arr2 = []; arr1 == arr2; // false 

Two literals always evaluate two different instances that are not considered equal.

+1
source share

In fact, I could not find the code to check whether the object is an array of length (for example, an empty array) anywhere, so I wrote it very quickly if someone wants it later:

  function isArrayOfLength(obj, length) { var isArrayOfSpecifiedLength = false; if(Array.isArray(obj)){ if(obj.length === length){ isArrayOfSpecifiedLength = true; } } return isArrayOfSpecifiedLength; } 

And tests for him:

  (function(){ var isValidArray = isArrayOfLength([], 0); console.log(isValidArray); //true })(); (function(){ var isValidArray = isArrayOfLength([1,2,3], 0); console.log(isValidArray); //false })(); (function(){ var isValidArray = isArrayOfLength([1,2,3], 3); console.log(isValidArray); //true })(); (function(){ var isValidArray = isArrayOfLength({notAnArray:true}, 0); console.log(isValidArray); //false })(); 

https://plnkr.co/edit/sjgnVoNAI0KUNCwhbdpx?p=preview

0
source share

All Articles