Why does changing one array alters the other?

前端 未结 8 1558
情歌与酒
情歌与酒 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:10

    Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.

    When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.

    You can see the same "they're pointing to the same object" behavior with Date instances:

    var d1 = new Date(), d2 = d1;
    d1.setMonth(11); d1.setDate(25);
    alert(d2.toString()); // alerts Christmas day
    

提交回复
热议问题