我一直在阅读克隆,每个人似乎都在使用一些复杂的代码。我想我可能做错了,但似乎工作正常,并且当改变"克隆"的价值时对象属性,我的主要对象不会改变。
var clonedObject ={};
//randomItem is main object, which I want to clone
for (var key in randomItem) {
if (randomItem.hasOwnProperty(key)) {
clonedObject[key] = {};
clonedObject[key] = randomItem[key];
}
};
return clonedObject;
它对我有用,请告诉我这是否有问题? 我很困惑,因为与其他帖子所说的相比,这似乎太容易了(其中一些是7岁)。感谢
答案 0 :(得分:1)
以下是一个快速示例,您可以看到代码与嵌套对象相比如何与真正的深度克隆相比:
var x = {a:{a:1}};
function update () {
document.getElementById('x').textContent = JSON.stringify(x);
document.getElementById('y').textContent = JSON.stringify(y);
document.getElementById('z').textContent = JSON.stringify(z);
}
// This is your code
function yourClone (randomItem) {
var clonedObject ={};
for (var key in randomItem) {
if (randomItem.hasOwnProperty(key)) {
clonedObject[key] = {};
clonedObject[key] = randomItem[key];
}
};
return clonedObject;
}
// This is a real deep clone taken from http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
function deepClone (obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = deepClone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
function inc() {
x.a.a++;
update();
}
<body onload="y=yourClone(x);z=deepClone(x);update()">
x: <span id="x"></span><br/>
y: <span id="y"></span> <- your clone from 'x'<br/>
z: <span id="z"></span> <- real deep clone from 'x'<br/><br/>
<button id="inc" onclick="inc()">Increment nested element in x</button>
</body>
当您将某个变量的值复制到另一个变量时,根据数据类型,您将复制值本身(数字和文本)或仅复制数据(日期,数组和对象)。处理引用时,您需要递归进入下一级别并将所有值复制到新对象中以创建新实例。
答案 1 :(得分:-1)
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
What is the most efficient way to deep clone an object in JavaScript?
在nodeJS中使用下划线模块让newObj = _.clone(oldObj);