Reputation: 2807
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!
Upvotes: 3
Views: 160
Reputation: 116498
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.
Upvotes: 7
Reputation: 8953
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
.
Upvotes: 2
Reputation: 3681
you are assigning the address value of array a and b into y and z. therefore, y, and z become the exact copy of a and b. instead of assigning address value into y and z. you just need to take content value of a and b and assign them into y and z y = a[0]
z = b[0]
and then y++
Upvotes: 0