JSON对象的jQuery克隆返回undefined

时间:2012-06-15 19:50:36

标签: jquery json clone

根据文档,jQuery.extend()是一个执行JSON对象的深层和浅层副本的解决方案。但是,当我使用它时,我得到一个未定义的对象错误。

我的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返回undefined。有和没有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"}
]

1 个答案:

答案 0 :(得分: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