我有一个情景,需要将对象数组(主数组)复制到另一个临时数组中,这个临时数组不应该与对象的引用相关联。如果我对主数组进行任何修改,不应该反映在临时数组中,这样我就可以独立地保存副本。
我使用了stackoverflow上的代码片段之一,它部分地实现了此目标,例如如果我从主数组中删除所有对象,则临时数组仍将保留值。但是当我对主数组进行某些修改并单击取消按钮时,我使用array.Removeall()从主数组中删除所有对象,但修改仍然存在于临时数组中,这意味着对象具有引用。
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;
}
我的对象结构如下所示
我正在使用 Knockout 框架。
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
var clone = JSON.parse(JSON.stringify(src));
- Yoshi