JS - Why are two empty arrays not equal?

var a = [], b = [];
console.log(a==b);

  What is the output of the console print? The answer is: false.

  Next look at the analysis:

  Comparison of primitive values ​​is a comparison of values:

    They are equal when their values ​​are equal (==)

    They are identical (===) when their value and type are equal.

  Objects are different from primitive values. Object comparisons are not value comparisons, but reference comparisons:

    Two objects are not equal even if they contain the same properties and the same values

    Two arrays are not equal even if their respective index elements are exactly equal

  Take a chestnut:

var o = {x:1}, p = {x:1};       // two objects with the same properties 
o == p                         // => false: two separate objects are never equal 
var a = [], b = [];             // two separate empty arrays 
a == b                         // => false: two separate arrays are never equal

  We usually refer to objects as reference types to distinguish them from JavaScript's primitive types. Object values ​​are references, and comparisons of objects are comparisons of references: they are equal if and only if they refer to the same base object.

  Take a chestnut:

var a = [];   // define a variable a that references an empty array 
var b = a;    // variable b references the same array 
b[0] = 1;     // modify the referenced array 
a[0]          through variable b // => 1: variable a also modifies 
a === b       // => true: a and b refer to the same array, so they are equal

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324819440&siteId=291194637