使用JSON.parse(JSON.stringify(obj))深度复制对象有哪些危险? [英] What are the dangers of Deep-copying objects using JSON.parse(JSON.stringify(obj))?

查看:93
本文介绍了使用JSON.parse(JSON.stringify(obj))深度复制对象有哪些危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JSON.parse(JSON.stringify(obj))是一个古老的技巧,我见过它用于深度复制对象. 它会创建对象的真正深层复制"吗? 性能方面,使用它是否明智?

Using JSON.parse(JSON.stringify(obj)) is an old trick i've seen used a lot for deep-copying objects. Does it create a truly 'deep-copy' of an object? Performance-wise, is it considered wise to use?

推荐答案

使用此方法深度复制对象的最大问题是该对象必须是JSON可序列化的事实.例如,以下对象:

The biggest problem with using this method to deep-copy an object is the fact the object must be JSON serializable. For example, the following object:

let obj = {
    func: function() {
        console.log("hello world!");
    }
}

由于函数不可JSON序列化,因此无法正确复制.还有许多其他问题,例如循环引用.这实际上仅适用于简单的普通对象,因此不是一个特别好的解决方案.我建议您检查一下下划线或lodash之类的内容,以进行高性能的深度复制.

Would not be copied properly since functions are not JSON serializable. There are many other issues as well, such as with cyclic references. This really only works for simple, plain objects and thus isn't a particularly good solution. I would recommend checking out something like an underscore or a lodash for high-performance deep copying.

这篇关于使用JSON.parse(JSON.stringify(obj))深度复制对象有哪些危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆