0

I have an array of objects (global scope):

objects =[{id:"0",radius:3,},{id:"1",radius:2,}].

This array is being manipulated by changing the single objects:

objects =[{id:"0",radius:4,},{id:"1",radius:5,}].

or by pushing new objects to the array:

objects =[{id:"0",radius:4,},{id:"1",radius:5,},{id:"2",radius:3,}].

After each manipulation, I want to save the entire array to another array called "history" to be able to recall each state.

I've tried:

var history_obj =[];

var history_index = 0;

function save_to_history(){history_obj[history_index]=objects; history_index++;} 

and also:

function save_to_history(){history_obj.push(objects); history_index++;} 

I've debugged the script and found out, that after running the save_to_history() function n times my history_obj contains a number of n arrays, however all arrays are the same (the one that would be supposed to be the last one to be pushed) not [[state1],[state2],[state3]] but [[state3],[state3],[state3]].

I've read in this forum, that this Problem has to do with the scope.

So I've tried:

function save_to_history(){
var status = objects; 
history_obj[history_index]=status;
history_index++;} 

The result is the same. Thanks in advance for your help.

Akim
  • 29
  • 4

3 Answers3

0

You can use JSON.stringify() to push the current array as a string to an array.

guest271314
  • 1
  • 15
  • 104
  • 177
0

You are adding the same reference into your history, you need to first clone it and then add it in, like so:

JSON.parse(JSON.stringify(arr));
Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
-1

This should solve the issue:

function save_to_history(){
    history_obj.push(JSON.parse(JSON.stringify(objects)))
}

as you need to deepcopy the object else it'll keep on changing, whenever your objects changes and consequently all the values will be same, which exactly is what you're getting.

Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39