使用JSON进行JavaScript深度复制 [英] javascript deep copy using JSON
问题描述
我对javascript对象(数组)深层复制有问题.我阅读了许多处理它的好方法.而且我也知道jQuery具有$ .extend API来解决此问题.但是我的问题是:我可以仅使用JSON stringify和parse方法来解决此问题吗?
I have problem with javascript object(array) deep copy. I read many good way to deal with it. And I also know that jQuery has $.extend API to this problem. But my question is: Can I just using JSON stringify and parse method to solve this problem?
这是我的代码:
function deepCopy(oldValue) {
var newValue
strValue = JSON.stringify(oldValue)
return newValue = JSON.parse(strValue)
}
var a = {
b: 'b',
c: [1,2,4],
d: null
}
copy = deepCopy(a)
console.log(a === copy) // false
console.log(a.c === copy.c) // false
PS:我知道,如果没有所有对象都可以序列化,但是我所知道的唯一情况是,当对象包含一个函数属性时.还有其他情况吗?
PS: I've known that if no all objects are serializable, but the only situation I know is that when the object contains a property which is function. Any other situation?
推荐答案
如果您的对象很小"并且仅包含可序列化的属性,那么使用JSON序列化的简单deepCopy hack应该可以.但是,如果您的对象很大,则可能会遇到问题.如果它包含不可序列化的属性,则这些属性将丢失:
If your object is "small" and contains exclusively serializable properties, a simple deepCopy hack using JSON serialization should be OK. But, if your object is large, you could run into problems. And if it contains unserializable properties, those'll go missing:
var o = {
a: 1,
b: 2,
sum: function() { return a + b; }
};
var o2 = JSON.parse(JSON.stringify(o));
console.log(o2);
收益:
Object {a: 1, b: 2}
足够有趣的是,C#中的大量深层复制解决方案都是类似的序列化/反序列化技巧.
附录:不确定在复制后比较对象方面的期望.但是,对于复杂的对象,通常需要编写自己的Compare()
和/或Equals()
方法以进行准确的比较.
Addendum: Not sure what you're hoping for in terms of comparing the objects after the copy. But, for complex objects, you generally need to write your own Compare()
and/or Equals()
method for an accurate comparison.
同样值得注意的是,这种副本不会保留类型信息.
Also notable, this sort of copy doesn't preserve type information.
JSON.parse(JSON.stringify(new A())) instanceof A === false
这篇关于使用JSON进行JavaScript深度复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!