Why does changing one array alters the other?

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

    All Javascript objects are passed by reference - you would need to copy the entire object, not assign it.

    For arrays this would be simple - just do something like:

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

    where slice(0) returns the array from offset 0 to the end of the array.

    This link has more info.

提交回复
热议问题