Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is variable updated "by reference"?

I have the following simple script.

<script>
SPC = {
    a : [10],
    b : 10,

    t: function()
    {
        y = this.a;
        z = this.b;
        y[0]++;
        z++;
        alert('this.a[0] = ' + this.a[0] + '\nthis.b = ' + this.b)
    }
}

SPC.t();
SPC.t();
</script>

Running it in your browser will display two alert boxes with:

this.a[0] = 11 this.b = 10

and

this.a[0] = 12 this.b = 10

The question is, why does the value of this.a[0] increment? I'm assigning "y = this.a" and updating element of "y" as "y[0]++;"?

At the same time, exactly the same thing is happening with "b": "z = this.b; z++". Yet, "this.b" remains equal to 10.

How can I change value of "y[0]" in the local scope without affecting "this.a"?

Any ideas?

Thanks!

like image 478
temuri Avatar asked May 22 '26 10:05

temuri


2 Answers

a is an array, and you're simply copying a reference to the array into y. You need to copy the array a's contents into a new array y instead (using Array.slice() (y = a.slice() in your case) is the easiest way).

(Or, if you only need a[0], you can set y = a[0]. Subsequent changes to y will not affect a[0], since you are copying the value.)

See the "Javascript Arrays Are Assigned By Reference" and "Passing Arrays As Values" sections of this article for more information.

like image 105
lc. Avatar answered May 24 '26 01:05

lc.


Try Array.slice() function.

y = this.a.slice()

This will create a copy of a array and assign it to y. So modification of y won't affect a.

like image 45
Rorick Avatar answered May 24 '26 00:05

Rorick