Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的闭包变量在JSON数据上使用$.each后被清除?_Javascript_Jquery_Json_Closures - Fatal编程技术网

Javascript 为什么我的闭包变量在JSON数据上使用$.each后被清除?

Javascript 为什么我的闭包变量在JSON数据上使用$.each后被清除?,javascript,jquery,json,closures,Javascript,Jquery,Json,Closures,考虑以下示例: var features = []; $.getJSON(annotations_url, function(data) { $.each(data, function(key, val) { features.push(wkt_parser.read(val.annotation.wkt_data)); // at this point, "features" contains objects }); }); annotationLayer.add

考虑以下示例:

var features = [];

$.getJSON(annotations_url, function(data) { 
  $.each(data, function(key, val) {
    features.push(wkt_parser.read(val.annotation.wkt_data));
    // at this point, "features" contains objects
  });
});

annotationLayer.addFeatures(features);
// here, it is empty again
在这里,我希望
功能不断增长。但是,在最后一行中,
features
再次为空


这是为什么?我如何从
$中正确地将值推送到
功能中。每个
(或者更确切地说是内部的匿名函数)

调用
$。getJSON
调用是异步的,因此
annotationLayer.addFeatures
可能是在JSON请求完成之前执行的。在
循环之后,在
$.getJSON
调用中调用
addFeatures
方法


如果您需要用<代码>特性执行更多的东西,请考虑创建一个新函数(其中包含需要调用的<代码> AddioDistaby/Cuth>方法),然后在

$.getJSON
调用中的每个
循环之后调用这个新函数。

这与
$.getJSON
函数的异步行为有关。移动
annotationLayer.addFeatures(特征)
$.getJSON
函数中

功能
变量未被“清除”;相反,在
annotationLayer.addFeatures(features)时没有填充它被执行