0

The JavaScript snippet is as follows:

var a = [1, 2, 3],
    b = [1, 2, 3],
    c = [1, 2, 4]
a ==  b
a === b
a >   c
a <   c

As my understanding, because array is object and when you compare two objects using '==' or '===', you actually compare their reference. So a == b and a === b all returns false. Right?

Considering a > c and a < c comparison, I tried in Chrome and a > c returns false, a < c returns true. As I googled, "Arrays are compared lexicographically with > and <". Does that mean 'a > c' logically equals to:

for (var i = 0; i < Math.min(a.length, c.length); i++) {
   if (a[i].toString() <= c[i].toString)   return false;
}
return true;

Am I right? If not, can anyone help explain the mechanism behind it? thanks a lot.

Lisa
  • 140
  • 1
  • 9

1 Answers1

0

It converts the arrays to strings, then compares them lexicographically. Converting an array to a string returns the result of array.join(','), so

[1, 2, 3] < [1, 2, 4]

is equivalent to

"1,2,3" < "1,2,4"

For an array of numbers this is effectively the same as your loop. It might not be equivalent for an array of strings.

For more information about how coercion is done in comparison operators see How do the JavaScript relational comparison operators coerce types?

Barmar
  • 669,327
  • 51
  • 454
  • 560