Why does changing one array alters the other?

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

    It's the same array (since it's an object, it's the same reference), you need to create a copy to manipulate them separately using .slice() (which creates a new array with the elements at the first level copied over), like this:

    var a = [1, 2, 3],
        b = a.slice();
    
    b[1] = 3;
    
    a; // a === [1, 2, 3]
    

提交回复
热议问题