1

So currently I have an Array here, and I want to make some modification of the last item and push it back it. Here I have this code: (example is simplified)

var array = [
                 [ [0,1,2], [3,4,5] ]
            ];

//other stuff...

var add = array[0].slice(); //to clone the array (but not working as expected)
add[0][0] = 10;
array.push(add);

console.log(array);

And here's the result

       enter image description here

As you can see, both the 1st and 2nd item have its first item changed to 10. How can I solve this problem? I have already cloned the array.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

2 Answers2

5

Array.prototype.slice() does shallow copy, so nested array are not copied. You should use deep clone method like this.

Community
  • 1
  • 1
Mics
  • 1,420
  • 14
  • 19
  • 1
    Ur answer is good but it would be nice if you spoke on the point that the array created by slice is new but the objects inside the original array are not copied but references – aaronman Jul 19 '13 at 04:00
  • @aaronman Agree. I think "shallow copy" explains it all, doesn't it? – Mics Jul 19 '13 at 04:04
1

Array.prototype.slice() does not clone nested array. you can do something like this particular to your problem

var array = [
                 [ [0,1,2], [3,4,5] ]
            ];

//other stuff...

var add = array[0].slice(); //to clone the array (but not working as expected)
add[0] = array[0][0].slice();
add[0][0] = 10;
array.push(add);

console.log(array);
Zahid Riaz
  • 2,879
  • 3
  • 27
  • 38