Javascript arrays cannot equal each other? -


this question has answer here:

i started with:

"1:2".split(':') == ["1","2"];  // false 

then tried:

[1,2] == [1,2]; // false 

and ultimately:

[] == [];  // false 

i've since found that:

"1:2".split(':').tostring() == [1,2].tostring(); // true 

so i've solved initial issue (kind of) why can't arrays match each other?

javascript arrays objects , can't use equality operator == understand if content of objects same. equality operator test if 2 object same instance (e.g. myobjvariable==myobjvariable, works null , undefined too).

if need check if 2 array equals i'd recommend traverse both arrays , verify elements have same value (and 2 array have same length).

regarding custom objects equality i'd build instead specific equals function , i'd add prototype of class.

considering in end converted both arrays string , tested equality of resulting strings, 1 day consider using similar more generic technique you'll find described in more few places:

json.stringify(obj1) === json.stringify(obj2)  

well, don't.

while work if order of properties same object instances, leaves door open extremely nasty bugs hard track down. favor more explicit approach , write clean , readable function test equality checking required fields.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -