[Javascript] Unexpected Result

liorean liorean at gmail.com
Tue Aug 3 16:14:28 CDT 2010


On 3 August 2010 22:40, Terry Riegel <riegel at clearimageonline.com> wrote:
> If I have something like this from the console...
>
> # QQ=$.a.LASTLOSER[2]
> 5
>
> # QQ=2
> 2
>
> # QQ
> 2
>
> # $.a.LASTLOSER[2]
> 5
>
> I would have expected the last line to be 2. Anyone have advise on why this is and how I can avoid this misconception in the future?

Simple: Javascript *always* passes things by value, not by reference.
The value may be a reference-type (objects, not primitives), but it's
the value that is passed around, not the reference.

So, what's happening is that you're extracting the value from
$.a.LASTLOSER[2] and store that value in QQ. Then you change the value
of QQ, read the value of QQ and read the value of $.a.LASTLOSER[2]. At
no time did you change the value of $.a.LASTLOSER[2], so naturally it
stays the same. If you want to do the equivalent of passing around
references, then you need to pass around a reference type from which
you read a property, and store new values in a property of that
object.
-- 
David "liorean" Andersson


More information about the Javascript mailing list