Why does changing one array alters the other?

前端 未结 8 1559
情歌与酒
情歌与酒 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条回答
  •  旧时难觅i
    2020-11-28 15:56

    the statement x = y is the only special one here, it means "point the variable x at the object y.

    Pretty much every other operation is an operation which changes the object referred to by x

    b = a;
    b[1] = 3;
    

    So, your first statement points the variable b at the array also referred to as a

    Your second statement alters the array pointed to by b (and also by a)

提交回复
热议问题