Why does changing one array alters the other?

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

    Assigning an array does not create a new array, it's just a reference to the same array. Numbers and booleans are copied when assigned to a new variable.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
提交回复
热议问题