[thelist] JavaScript array problem

Karl Bunyan freelance at core10.co.uk
Fri Aug 8 17:11:47 CDT 2003


That's the way I read it as well. If you want both arrays to hold the
same contents initially then you'll need something like

for(var i=0;i<array1.length;i++){
	array2[i]=array1[i];
}

in place of array2=array2. And I second that recommendation of the
O'Reilly book.

Karl

> -----Original Message-----
> From: thelist-bounces at lists.evolt.org 
> [mailto:thelist-bounces at lists.evolt.org] On Behalf Of Simon Willison
> Sent: 08 August 2003 22:50
> To: Fernando J. Gomez
> Cc: thelist at lists.evolt.org
> Subject: Re: [thelist] JavaScript array problem
> 
> 
> 
> 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



More information about the thelist mailing list