许多同行在这里提出的深度克隆解决方案 JSON.parse(JSON.stringify(orig_obj)
存在几个问题,我发现了以下问题:
- 它在复制原始对象时会丢弃值为
undefined
的条目
- 如果有一些像
Infinity
、 NaN
等的值,则在复制时它们将被转换为 null
- 如果原始对象中有一个
Date
类型,则它将在克隆对象中被字符串化( typeof date_entry --> string
)
找到了一种有效的方式来克隆对象,并且在各种情况下都运作良好。请查看下面的代码,因为它已经解决了所有上述 JSON.parse(...)
的缺点,同时产生了适当的深层克隆:
var orig_obj = {
string: 'my_str',
number: 123,
bool: false,
nul: null,
nested : {
value : true
},
nan : NaN,
date: new Date(),
undef: undefined,
inf: Infinity,
}
console.log("original_obj before modification: ", orig_obj, "\n");
console.log(typeof orig_obj.date, "\n");
var clone_obj = Object.assign({}, orig_obj);
for(let prop in orig_obj) {
if(typeof orig_obj[prop] === "object") {
if(orig_obj[prop] instanceof Date)
clone_obj[prop] = orig_obj[prop];
else {
clone_obj[prop] = JSON.parse(JSON.stringify(orig_obj[prop]));
}
}
}
console.log("cloned_obj before modification: ", orig_obj, "\n");
clone_obj.bool = true;
clone_obj.nested.value = "false";
console.log("original_obj post modification: ", orig_obj, "\n");
console.log("cloned_obj post modification: ", clone_obj, "\n");
console.log(typeof clone_obj.date);
mObj=JSON.parse(JSON.stringify(jsonObject));
。 - Lord Loh.Object.create(o)
,它完全满足了作者的要求。 - froginvasionvar x = { deep: { key: 1 } }; var y = Object.create(x); x.deep.key = 2;
执行完这段代码后,y.deep.key
的值也会变成2,因此 Object.create 不能用于克隆对象。 - Ruben Stolk