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.

0

3 Answers 3

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this seems to do the job.
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));

1 Comment

Thank you very much, this seems to do the job.
-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.

1 Comment

Thank you very much, this seems to do the job.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.