-1

Look at this JS code:

var st, ary, ary1, ary2;
ary  = [["a","b","c"], ["d","e","f"]]; // 2D array
ary1 = ary[1];
st   = "d,e,f"; ary2 = st.split(',');
st   = typeof(ary1) + " " + ary1.length + " " + ary1 + '\n';  // I put all output into a string 
st  += typeof(ary2) + " " + ary2.length + " " + ary2 + '\n'; // for a single display
st  += (ary1[0]==ary2[0])+'\n';
st  += (ary1==ary2);

console.log(st);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Output:
object 3 d,e,f
object 3 d,e,f
true
false

... Same but different! Why's that?

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Apostolos
  • 3,115
  • 25
  • 28
  • See https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript – jarmod Mar 14 '21 at 19:12
  • 4
    That is one twisted way of testing equality – geoffrey Mar 14 '21 at 19:15
  • 1
    You are not comparing arrays but 2 objects which each have a different memory address – Mister Jojo Mar 14 '21 at 19:16
  • 1
    compare as `ary1.toString() == ary2.toSting()` – Adarsh Mohan Mar 14 '21 at 19:17
  • Oh, and @geoffrey, this is not a "twisted" way of testing equality, It is a "wrong" way. Be more polite, please. And you had to specify **"arrays"**, because this testing is fine for strings. – Apostolos Mar 15 '21 at 01:52
  • Apostolos, I'm sorry, I didn't mean to be impolite. Your code is unnecessarily complicated. You didn't need state, you didn't need a 2D array, defining all your variables at the top and doing multiple assignments on the same line also made it harder to read. `const a = [1, 2, 3]; const b = [1, 2, 3]; a.toString() == b.toString(); // true a == b; // false` would have been both correct and simple – geoffrey Mar 15 '21 at 12:59
  • OK. The code is not complicated. Actually, **just the last check was enough**. But since I didn't know about the impossibility to compare two **"objects"**, I examined partial comparisons, to show that in all aspects the two arrays were equal. That's all. And thanks to **Mister Joho**, I am now aware of that. – Apostolos Mar 16 '21 at 17:20
  • Thanks, all of you! – Apostolos Mar 16 '21 at 17:21

2 Answers2

0

Because == checks if its actually the same object by checking the reference. It does not care about the content of the object. You could even deep clone the array to another array, it would still be different.

Consider this:

Person object1 = new Person("1", "Thomas", "Meier");
Person object2 = new Person("1", "Thomas", "Meier");
Person object3 = object1;

System.out.println(object1 == object2);
// Output: false
System.out.println(object1 == object3);
// Output: true
-1

Because they have different links. When you have created an array the var got a link. When you try to compare two arrays, js compares links.

Andrey RF
  • 342
  • 3
  • 13