[thelist] JavaScript array problem

Simon Willison cs1spw at bath.ac.uk
Fri Aug 8 16:49:53 CDT 2003


Hi Fernando,

Friday, August 8, 2003, 10:40:58 PM, you wrote:
> Note that I'm only modifying array1, but as the alerts show, array2 is also
> changing! It is as if both array1 and array2 were two names for the same
> array. I hadn't noticed this kind of behavior in JS before.

That's because they are, thanks to this line in your code:

> array1 = array2;

Arrays are objects in Javascript (run 'alert(typeof new Array);' for
evidence of this). In javascript, Objects are handled by reference.
When you assign array2 to array1 in the above line, you cause array1
to become a refernce to the same array as array2. Remove that line and
everything should work fine. Note that while objects are handled by
reference, core values like numbers and booleans are handled by value
(strings are also effectively handled by value, although there's a bit
more to it than that - consult a good Javascript reference for more
info).

Incidentally, I recently bought the O'Reilly book "Javascript: The
Definitive Guide" and it has superb coverage of the core Javascript
language covering 11 chapters, which includes detailed coverage of
this issue.

Cheers,

Simon


-- 
http://simon.incutio.com/



More information about the thelist mailing list