0

根据文档,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返回未定义。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"}
]
4

1 回答 1

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
于 2012-06-15T19:57:38.920 回答