Javascript:将对象数组推送到数组 [英] Javascript: Push array of objects to array

查看:96
本文介绍了Javascript:将对象数组推送到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组(全局范围):

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,}].

每次操作后,我想将整个数组保存到另一个名为 history的数组中,以便能够回忆起每个州。

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

我尝试过:

var history_obj =[];

var history_index = 0;

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

,并且:

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

我调试了脚本,发现在运行save_to_history()函数之后我的history_obj包含n个数组,但是所有数组都是相同的(应该被推为最后一个数组)不是[[state1],[state2],[state3]]而是[[

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.

所以我试过:

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.

推荐答案

您要将相同的引用添加到历史记录中,首先需要克隆它,然后添加它,就像这样:

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));

这篇关于Javascript:将对象数组推送到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆