2012-06-15 117 views
0

根據文檔,jQuery.extend()是同時執行JSON對象的深度和淺度副本的解決方案。但是,當我使用這個,我得到一個未定義的對象錯誤。JSON對象的jQuery克隆返回undefined

我的Ajax請求的功能和處理程序:

var tourData; 

$.ajax({ 
    type: "GET", 
    url: "includes/phpscripts.php?action=stops", 
    dataType: "json", 
    success: (function(data){ 
    if (data == 'false') 
     console.log("Can't load initial panorama"); 
    else 
     processOptions(data); 

    }) 
}); 

function processOptions(data){ 
    tourData = jQuery.extend(true, {}, data); 
    console.log(data.length); 
    console.log(tourData.length); 

} 

在Firebug中,data.length返回6,這是我所期待的。但tourData返回未定義。這發生在有和沒有true作爲深拷貝的參數

我將需要這個請求中的數據以後可用於幾個函數,這些函數將超出範圍。因此,我希望有一個克隆的響應可用。

data內容是

[ 
    {"fileName":"..\/panos\/photos\/1-prefix_blended_fused.jpg","name":"Start","lat":"43.682211","lon":"-70.450705","heading":"250","width":"1808","height":"653"}, 
    {"fileName":"..\/panos\/photos\/2-prefix_blended_fused.jpg","name":"Second","lat":"43.6822","lon":"-70.450769","heading":"250","width":"1600","height":"578"}, 
    {"fileName":"..\/panos\/photos\/2-prefix_blended_fused.jpg","name":"Second","lat":"43.6822","lon":"-70.450769","heading":"250","width":"1600","height":"578"}, 
    {"fileName":"..\/panos\/photos\/3-prefix_blended_fused.jpg","name":"Third Stop","lat":"43.682219","lon":"-70.450828","heading":"250","width":"1821","height":"627"}, 
    {"fileName":"..\/panos\/photos\/4-prefix_blended_fused.jpg","name":"Fourth Stop","lat":"43.68218","lon":"-70.450887","heading":"250","width":"1600","height":"800"}, 
    {"fileName":"..\/panos\/photos\/5-prefix_blended_fused.jpg","name":"Last Stop","lat":"43.682165","lon":"-70.450933","heading":"250","width":"1808","height":"673"} 
] 
+0

datA的內容是什麼 –

+0

好像'data'是一個數組。 'console.log(data)',讓我們看看裏面有什麼。 –

+0

是的,數據是一個數組,而不是一個對象。你想要'$ .extend'在這裏做什麼?你想要的輸出是什麼? –

回答

2

你說 data.length是6。這讓我覺得, data是一個數組,而不是一個對象。

data不是一個對象,它是一個數組。

$.extend將與數組一起工作,但length屬性將不再存在,因爲它會將其轉換爲對象。

var data = [{a:12}, {a:13}, {a:14}]; 
console.log(data.length); // 3 
data = $.extend(true, {}, data); 
console.log(data); // {0:{a:12}, 1:{a:13}, 2:{a:14}} 
console.log(data.length); // undefined 
+0

這是解決方案。謝謝! – Jason

+0

不客氣:-) –