+ 1

Why output is false

var a=[1,2]; var b=[1,2]; document.write(a===b)

31st Jul 2018, 10:18 AM
Cлaвeн Ђервида
Cлaвeн Ђервида - avatar
4 Réponses
+ 9
Arrays in JavaScript are classified as objects. Objects are compared by reference using == or ===. If two objects points to the same memory location, they are considered equal. So, in your code sample, since both array a and b are declared and assigned a value, they are not equal even if they have the same array values. They point to two different memory locations.
31st Jul 2018, 10:45 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 1
When you compare objects JS compares their references which are unique to the object if you do a === a you will recieve true because the operands have the same reference.
31st Jul 2018, 10:38 AM
TurtleShell
TurtleShell - avatar
+ 1
thank you guys so much help
31st Jul 2018, 10:47 AM
Cлaвeн Ђервида
Cлaвeн Ђервида - avatar
0
You could try something like this instead. function sameArray(arr1, arr2){ if (arr1.length !== arr2.length){ return false; } for (var x = 0; x < arr1.length; x++){ if (arr1[x] !== arr2[x]){ return false; } } return true; } document.write(sameArray(a, b));
31st Jul 2018, 11:59 AM
James
James - avatar