2012-02-14 67 views
11

我想使用jQuery $ .extend合併兩個對象。

使用下面的代碼,我試圖提醒(「球 - 樹樁 - 裁判員」)。但目前的輸出是(「未定義 - 樹樁 - 裁判員」)。它不能實現深層(遞歸)複製。我們如何解決這個問題?

$(document).ready(function() { 

     debugger; 

     //$.extend 
     var obj3 = { throwable: { text1: 'Ball' }, text3: 'Umpire' }; 
     var obj4 = { throwable: { text4: 'Bat' }, text2: 'Stump' } 

     //Simple Copy 
     var result1 = $.extend(obj3, obj4); 
     //alert(result1.throwable.text4 + " - " + result1.text2 + " - " + result1.text3); 


     //Deep Copy 
     //First parameter is passed as Boolean true to accomplish deep (recursive) copy 
     var result2 = $.extend(true, obj3, obj4); 
     alert(result2.throwable.text1 + " - " + result2.text2 + " - " + result2.text3); 


    }); 

編輯:我提到

(Deep) copying an array using jQuery

+0

** ** ** **這些問題:'asp.net''.net'' jquery-ui'' jquery-plugins'標籤相關的問題是什麼? – gdoron 2012-02-14 09:13:55

回答

7

你的第二個代碼片段確實如預期工作,並在隔離運行時執行的obj4深拷貝到obj3

問題是,前面的代碼片段已經執行的一個obj4拷貝obj3,完全覆蓋其throwable構件與過程obj4的。因此,在代碼運行後,在obj3內不再存在。

  • 最初,obj3是:

    { throwable: { text1: 'Ball' }, text3: 'Umpire' } 
    
  • 第一代碼段運行後,obj3變爲:

    { throwable: { text4: 'Bat' }, text3: 'Umpire', text2: 'Slump' } 
    
  • 最後,第二代碼段已經運行之後,obj3仍然是:

    { throwable: { text4: 'Bat' }, text3: 'Umpire', text2: 'Slump' } 
    
+0

感謝您的清楚解釋。 – Lijo 2012-02-14 11:23:01

0

在你的代碼,text1屬性由extend覆蓋。如果你想要一個包含字符串的方法,你自己編碼,extend不這樣做。

喜歡的東西:

function(o1, o2) { 
    var ores = {}; 
    for(var p in o1) ores.p = o1.p; 
    for(var p in o2) ores.p = ores.p ? ores.p+o2.p : o2.p; 
    return ores; 
} 
+0

@Lijo如果你想看到不同之處:[see](http://api.jquery.com/jQuery.extend/) – Hadas 2012-02-14 09:03:08

+0

做一個遞歸合併不會連接srting! – sinsedrix 2012-02-14 09:05:09

+0

所以它似乎現在...現在有什麼問題? – sinsedrix 2012-02-14 09:21:05

0

的問題是,有與對象名稱相同的兩個屬性:text1的。即使深入擴展,jquery擴展也不會將它合併到一個新的concat字符串或數組中。

如果您的某個屬性是另一個對象,則深度複製是相關的。通過深度擴展,可以合併子對象的所有屬性,而不僅僅是子對象本身。

我認爲你必須去用你自己的擴展函數。