Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery array comparison with ==?

Tags:

arrays

jquery

I have two jQuery arrays initialList and newList.

I first compare them like so:

initialList == newList

This returns false.

Then I compare element by element:

$.each(initialList, function(idx, element){ console.log(element == newList[idx] )});

Every comparison is true.

So if all elements are identical why return false in the first comparison?

like image 927
Virgiliu Avatar asked Oct 16 '12 08:10

Virgiliu


People also ask

Can you compare arrays with ==?

equals() to compare two arrays is often misconstrued as content equality, and because a better alternative exists in the use of reference equality operators, the use of the Object. equals() method to compare two arrays is disallowed.


1 Answers

You're asking if they're equivilent (all items the same), whereas the == operator is checking if they are the same thing (references to the same object). They're not, so == returns false.

If you're asking philosophically why == doesn't evaluate the operands and tell you if for all intents and purposes they're 'the same', you can read more about equivalence verses equality on Wikipedia (Object identity vs. Content equality).

like image 163
Steve Wilkes Avatar answered Oct 10 '22 04:10

Steve Wilkes