【发布时间】:2012-04-10 18:21:35
【问题描述】:
我有一个场景,我需要将对象数组(主数组)复制到另一个临时数组,如果我对主数组进行任何修改,它基本上不应该有对象引用,它不应该反映在临时数组中,这样我将独立保存副本。
我使用了堆栈溢出中的代码 sn-p 之一,这部分类似于如果我从主数组中删除所有对象,临时数组仍然保留该值,但是当我在主数组中进行一些修改并单击取消按钮时我正在使用 array.Removeall() 从主数组中删除所有对象;但修改仍然存在于 Temp 数组中,因此这意味着该对象具有引用。
clone: function (existingArray) {
var newObj = (existingArray instanceof Array) ? [] : {};
console.debug('newObj value is ' + newObj);
for (i in existingArray) {
console.debug('i value is' + i);
if (i == 'clone') continue;
console.debug('existingArray[i] value ' + existingArray[i]);
if (existingArray[i] && typeof existingArray[i] == "object") {
newObj[i] = this.clone(existingArray[i]);
} else {
console.debug('in else part ' + existingArray[i]);
newObj[i] = existingArray[i];
}
}
return newObj;
}
我的对象结构是这样的
我正在使用淘汰赛框架。
newObjectCreation = function (localIp, RemoteIp, areaId) {
this.localIP = ko.observable(localIp);
this.remoteIP = ko.observable(RemoteIp);
this.areaId = ko.observable(areaId);
};
template.ProtocolArray.push(new newObjectCreation('', '', '')); // to create default row
请在这方面帮助我。 提前致谢。
【问题讨论】:
-
对象是否包含无法表达为JSON(不是对象文字)的任何内容?如果没有,你可以简单地做:
var clone = JSON.parse(JSON.stringify(src));
标签: javascript