SPC = { a : [10], b : 10, t: function() { y = this.a; z ...">

Is the variable "by reference" changed?

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>

Launching in the browser will display two notification windows:

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

and

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

The question is why the value of this.a [0] is increasing? I assign "y = this.a" and update the element "y" as "y [0] ++;"?

At the same time, the same thing happens with "b": "z = this.b; z ++". However, "this.b" remains at 10.

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

Any ideas?

Thanks!

+3
source share
3 answers

a - , y. a y ( Array.slice() (y = a.slice() ) ).

(, a[0], y = a[0]. y a[0], .)

. " Javascript- " " " .

+7

Array.slice().

y = this.a.slice()

a y. y a.

+2

you assign the address value of the array a and b to y and z. therefore, y and z become an exact copy of a and b. instead of assigning the address value to y and z. you just need to take the content value of a and b and assign them to y and z y = a [0]

z = b [0]

and then y ++

0
source

Source: https://habr.com/ru/post/1705567/


All Articles