0

I'm trying to create a script for building an undo / redo function. Idea is my object should be added to a new key in array whenever it's updated.

I tested it with the following script :

var undoredo = new Array();
var obj = {
    "0": {
            "bg-pos": "",
            "zoom": 3
        }
}  

for($i=1; $i < 5; $i++) {
  obj[0]['zoom'] = obj[0]['zoom']+1;
  undoredo.push(obj);
}

The problem here is zoom value should have been increased in each array key (3 to 7) but instead all zoom values are ended up with 7, the last added object's value. Is there any other way to add objects into array?

Mertafor
  • 374
  • 4
  • 17
  • 1
    There are many duplicates. I'll try to find one. In short, however: You only have one object, which you insert into the array multiple times. – Quentin Oct 08 '17 at 08:45
  • You should consider using http://jshint.com — you have some non-idiomatic code there as well as a potentially problematic implicit global. – Quentin Oct 08 '17 at 08:48
  • In case it helps someone the right way to do it is to clone / copy of original object. Here is the best answer I found : https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Mertafor Oct 08 '17 at 09:10

0 Answers0