+ 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”);

22nd Sep 2018, 12:04 PM
Daniel
Daniel - avatar
6 odpowiedzi
+ 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
22nd Sep 2018, 1:00 PM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar
+ 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.
22nd Sep 2018, 12:28 PM
ifl
ifl - avatar
+ 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
22nd Sep 2018, 6:08 PM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar
+ 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?
22nd Sep 2018, 5:21 PM
Daniel
Daniel - avatar
+ 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).
22nd Sep 2018, 9:55 PM
Dmitry
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.
24th Sep 2018, 2:11 PM
Mr Genesis
Mr Genesis - avatar