jquery.extend(true,[],obj)没有创建深层副本 [英] jquery.extend(true, [], obj) not creating a deep copy

查看:106
本文介绍了jquery.extend(true,[],obj)没有创建深层副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jsFiddle here

如果深度复制工作,输出将是好奇的乔治而不是安德的游戏。我怎样才能制作深层照片? 此问题的答案表明 $ .extend(true,[],obj)创建一个深层副本。然而我的例子显示它没有。

If deep copying worked, the output would be "Curious George" and not "Ender's Game". How can I make a deep copy? An answer to this question indicates that $.extend(true, [], obj) creates a deep copy. Yet my example shows that it doesn't.

function Person(){}
Person.prototype.favorite_books = [];

var george = new Person();
george.favorite_books = ["Curious George"];

var kate = new Person();
kate.favorite_books = ["The Da Vinci Code", "Harry Potter"];

var people = [kate, george];

var people_copy = $.extend(true, [], people);
people_copy[0].favorite_books[0] = "Ender's Game";

$('#text').text(people[0].favorite_books[0]);

解决方案

我更新了jsFiddle。事实证明我需要单独深度复制数组中的每个对象如果对象是自定义对象(即 $。isPlainObject 返回false )。

I updated the jsFiddle. It turns out I need to deep copy each object in the array individually if the object is a custom object (that is, $.isPlainObject returns false).

推荐答案

现在这里是真正的答案:

目前,jQuery只能克隆纯JavaScript对象,而你正在使用自定义JavaScript对象。这很明显,因为jQuery无法知道如何实例化一个新的自定义对象。所以这可以按预期工作:

At the moment jQuery can only clone plain JavaScript Objects, while you're using custom ones. And that's obvious, since jQuery cannot know how exactly to instantiate a new custom object. So this works as expected:

var george = {};
george.favorite_books = ["Curious George"];

var kate = {};
kate.favorite_books = ["The Da Vinci Code", "Harry Potter"];

var people = [kate, george];

var people_copy = $.extend(true, [], people);

console.log(people_copy[0].favorite_books == people[0].favorite_books);

对jQuery代码的引用: https://github.com/jquery/jquery/blob/master/src/core.js#L305

Reference to a jQuery code: https://github.com/jquery/jquery/blob/master/src/core.js#L305

看到它检查它是否是 jQuery.isPlainObject(copy)或者它是一个数组。否则它只执行参考副本。

See that it checks if it's jQuery.isPlainObject(copy) or it's an array. Otherwise it performs just a reference copy.

这篇关于jquery.extend(true,[],obj)没有创建深层副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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