0
function setobjprop(ind, prop, v) {
    if (undo_arr.length > 0) {
        console.log("C" + undo_arr.length + ": " + undo_arr[0][0].rotate);
    }
    console.log(ind + ":" + prop + ":" + v);
    user_img[ind][prop] = v;
    if (undo_arr.length > 0) {
        console.log("D" + undo_arr.length + ": " + undo_arr[0][0].rotate);
    }
    undo_arr.push(user_img.slice(0));
    console.log(undo_arr[0][0].rotate);
    console.log(prop + " -> " + v);
    if (undo_arr.length > 10) {
        undo_arr.shift();
    }
    redrawCanvas(ind);
}

I have an array of objects called user_img, now I wrote a function to update the value of an object at a particular index within this array, then I am trying to store a copy of this entire array in another array called undo_arr. But all copies of the array in the undo_arr seems to point to the user_img array, because the object modification seems to reflect upon all copies previously stored in the undo_arr. Any idea what I am doing wrong?

Bluemagica
  • 5,000
  • 12
  • 47
  • 73
  • 1
    You are not creating a copy of the array. You simply add a reference to it. If you want to create a deep copy (i.e. copy the array and the objects it contains) have a look at http://stackoverflow.com/q/122102. – Felix Kling Jun 12 '13 at 12:49
  • When you assign a variable (or array element) to a variable that references an object, you end up with two references to the same object. – nnnnnn Jun 12 '13 at 12:51
  • but shouldn't slice(0) copy a new version of the array over? If not How can I copy it? – Bluemagica Jun 12 '13 at 12:52
  • You didn't have `.slice` before in your code ;) It only creates a shallow copy, not a deep one, i.e. the objects the array contains are not cloned. See the link in my first comment. Especially this answer: http://stackoverflow.com/a/122190. You probably want `undo_arr.push(clone(img_arr));`. – Felix Kling Jun 12 '13 at 12:53

0 Answers0