Reputation: 11459
I am confused about javascript comparison. let's say :
var array1 = [1,2,3];
var array2 = [1,2,3];
array1 == array2 ;
false // why false ?
array1 === array2;
false // also why false?
Can anyone explain this to me clearly? Thank you in advance.
Upvotes: 2
Views: 331
Reputation: 322492
They are false because you are comparing two different Array instances. It will only be true if they are actually references to the same instance.
var array1 = [1,2,3];
var array2 = array1;
array1 == array2 ; // true
To compare their content, you need to compare each item individually. Something like this, though this doesn't look any deeper than the one level.
var array1 = [1,2,3];
var array2 = [1,2,3];
function compareArrays(a1,a2) {
var len = a1.length;
if( len !== a2.length )
return false;
while( len-- ) {
if( a1[ len ] !== a2[ len ] ) {
return false;
}
}
return true;
}
compareArrays( array1, array2 ); // true
Upvotes: 4
Reputation: 44929
"Objects, arrays, and functions are compared by reference."
-- O'Reilly's JavaScript: The Definitive Guide
In your case array1
is a reference to a different Array than array2
.
See here for a way to compare Arrays.
Upvotes: 4