为什么我的闭包变量在使用$后被清除.每个都使用JSON数据

Why is my closure variable cleared after using $.each on JSON data?

本文关键字:清除 数据 JSON 闭包 我的 变量 为什么      更新时间:2023-09-26

考虑以下示例:

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会持续增长。然而,在最后一行中,features又为空。

为什么是这样,我如何正确地将值从$.each内推到features(或者更确切地说,内部的匿名函数)?

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

如果您需要使用features执行更多内容,请考虑创建一个新函数(其中包含您需要调用的addFeatures方法),然后在$.getJSON调用中的.each循环之后调用这个新函数。

这与$.getJSON函数的异步行为有关。将annotationLayer.addFeatures(features);移到$.getJSON函数中

features变量没有被"清除";相反,当执行annotationLayer.addFeatures(features);时,它没有被填充。