jsFiddle here。jquery.extend(true,[],obj)不創建深度複製
如果深度複製工作,輸出將是「好奇的喬治」,而不是「恩德的遊戲」。我怎樣才能做一個深層複製?對this question的回答表示$.extend(true, [], obj)
創建了一個深層副本。然而我的例子表明它沒有。
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]);
SOLUTION
我更新的jsfiddle。事實證明,如果對象是自定義對象(即,$.isPlainObject
返回false),我需要深度複製陣列中的每個對象。
使用.clone()請參閱http://api.jquery.com/clone/ – 2013-05-12 22:44:11
@Paul Sullivan:'.clone()'將與DOM實體 – zerkms 2013-05-12 22:44:44
一起使用,所以請瀏覽.extend源代碼並查看原因遞歸函數不復制屬性 – 2013-05-12 22:45:48