+ 4
Can someone explain to me why this is false?
var a = new array (âAâ, âBâ); var b = new array (âAâ, âBâ); Alert(a==b? âRedâ:âBlueâ);
6 Respostas
+ 6
Daniel,
In additional to ifl's answer.
If you join the 2 new created objects together, then it will be equalđ
var a = new Array ("a","b");
var b = new Array ("a","b");
alert(a.join(b)==b.join(a) ? "true":"false");
// Output = true
Preview:
https://code.sololearn.com/WfHk2m9u4nCI/?ref=app
+ 4
This is because a and b are not the same:
they have the same type and the same content, but physically were created at 2 different location in memory ,
and you can modify the content of var a without modifying the content of var b.
+ 3
The join() method joins all elements of an array(object) into a string and returns it.
Syntax:
Element.join(separator);
You can join the 2 array elements together and add some separators between each element.
Therefore, for my understanding, array elements cannot be equal(separately its possible arr[0]), but when they converted to string with join() it can be measured to be equal. If an element is undefined/null, it is converted to be an empty string.
(((Correct if I'm wrong, thanks))
Here in the provided source is it more briefly explained. Hope it helpsđ
https://www.w3schools.com/jsref/jsref_join.asp
+ 1
ifl thanks for that explenation... and thank you đŽVincent BergerđŽ that is interesting but also a bit confusing to me. If you dont mind can you explain to me why joining them before conparing them makes it true? Is it because now you are comparing the same 2 values that have the same addresses?
+ 1
As stated earlier, a and b are stored in different parts of memory, and each variable may be treated as link to this object, so a is not b (links lead to different places in memory). Iâm not sure how this is in JavaScript, in Java all objects variables are these links (including arrays and strings). Only primitive types can be compared using == (even though they may also be stored in different parts of memory).
0
Hey!
array a and array b it is two diferent objects. Just the content is equal it.
Exemple: two 0km car, is equal, but is diferents.
If you understand how variable is storage you will see that this two objects is in diferent local.