Martin said:
Archos said:
How to know if 2 arraies are equal? I was expecting that it could be
checked so:
var array1 = [1,2,3,4], array2 = [1,2,3,4];
if (array1 === array2) { console.log("array1 and array2 are equal"); }
Since the comparing of strings or integers works:
var a = "2", b = "2";
if (a === b) { console.log("a == b"); }
No, for objects (and arrays are objects) the identity is checked, no
comparison of properties or elements is done.
So with e.g.
var a1, a2;
a1 = a2 = [1, 2, 3, 4];
a1 == a2
you get true as the two variables hold references to the same array
object.
Correct. That example might be confusing, though.
If you want to compare the elements you will need to define and
implement your own comparison function I think
Not necessarily. One way without a custom comparison function that works
for *simple* cases like this is to compare the string representations of the
Array instances, which are (without overwriting the toString() method) the
comma-separated string representations of the corresponding array's
elements:
/* "1,2,3,4" == "1,2,3,4" */
a1.toString() == a2.toString()
or
String(a1) == String(a2)
or
("" + a1) == ("" + a2)
That is, those two arrays are considered equal if the string representations
of their elements are the same and occur in the same order (if we assume
that both instances use the same toString() method).
The caveat is that the string representations of elements can be the same,
although the elements are different. Consider this:
var o = {foo: 'bar'};
var o2 = {bar: 'baz'};
/* "[object Object]" == "[object Object]" */
[o].toString() == [o2].toString()
Instead of the `==' operator, the `===' operator may be used as well, but it
is neither supposed to add efficiency nor would it add expressive power
(both arguments are of the same type), while it certainly reduces the
backwards-compatibility of the entire code.
PointedEars
--
If you get a bunch of authors […] that state the same "best practices"
in any programming language, then you can bet who is wrong or right...
Not with javascript. Nonsense propagates like wildfire in this field.
-- Richard Cornford, comp.lang.javascript, 2011-11-14