Why does changing one array alters the other?

前端 未结 8 1554
情歌与酒
情歌与酒 2020-11-28 15:48

Consider this tiny bit of javascript code:

var a = [1, 2, 3],
    b = a;

b[1] = 3;

a; // a === [1, 3, 3] wtf!?

Why does \"a\" change when

8条回答
  •  日久生厌
    2020-11-28 16:11

    There is a difference between Value types and Reference types.

    Basicly Value types are stored on the computers "Stack" directly which means that you actualy have the "Value" and not what is called a Pointer/Reference.

    A Reference Type on the other hand, does not hold the actual value of the object/variable but instead it points ( references ) to where you can find the value.

    Thus when you say "My Reference Type B points to what Reference Type A points to", you actually have two variables pointing in the same direction and when you interact with either of them and change something, both will be pointing to the changed place, since the pointed to the same place from the begining.

    In your other case you say "Hey, copy the value in variable A to variable B" and thus you have the values on seperate places which means that any change to either of them will not affect the other.

提交回复
热议问题