问题描述
克隆JavaScript对象的最有效方法是什么?我见过 obj = eval(uneval(o));
正在使用,但。
我做过像<$ c $这样的事情c> obj = JSON.parse(JSON.stringify(o)); 但质疑效率。
我也看到了具有各种缺陷的递归复制功能。
我很惊讶没有规范的解决方案。
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o));
being used, but that's non-standard and only supported by Firefox.
I've done things like obj = JSON.parse(JSON.stringify(o));
but question the efficiency.
I've also seen recursive copying functions with various flaws.
I'm surprised no canonical solution exists.
推荐答案
我想注意方法仅克隆DOM元素。为了克隆JavaScript对象,你可以这样做:
I want to note that the .clone()
method in jQuery only clones DOM elements. In order to clone JavaScript objects, you would do:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
更多信息可以在。
我还要注意深层副本实际上比什么更聪明如上所示 - 它可以避免许多陷阱(例如,尝试深度扩展DOM元素)。它经常在jQuery核心和插件中使用,效果很好。
I also want to note that the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (trying to deep extend a DOM element, for example). It's used frequently in jQuery core and in plugins to great effect.
这篇关于在JavaScript中深度克隆对象的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!