Javascript:匿名函数,访问全局变量

Vio*_*lle 11 javascript anonymous function

经过几个小时的搜索,我的代码有问题.事实上,我认为我的答案并不是很远,但我仍然被封锁......

我有一个在循环内部调用的匿名函数,我想访问并刷新全局变量,但我尝试使用window.myvariable,使用另一个函数,没有任何反应......

我的代码:

for (var i = 0; i < SHP_files.length; i++) {
            shapefile = new Shapefile({
                shp: "shp/polygon/"+SHP_files[i]+".shp",
                dbf: "shp/polygon/"+SHP_files[i]+".dbf",
                }, function(data) {

                    polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
                    polygon_layer.addTo(map);
                    console.log(polygon_layer.getLayers()); // IS OK
                });
        };
        console.log(polygon_layer.getLayers()); // IS EMPTY !!
Run Code Online (Sandbox Code Playgroud)

那么,我如何才能转换这个匿名函数,以便能够从我的代码中访问哪些内容?

非常感谢,抱歉我的英语不太好......

Ste*_*eve 5

这是异步代码执行的典型问题。您的示例代码不会从上到下执行。特别是,匿名函数Shapefile只有在完成所执行的任何操作后才会执行。同时,您的JS将按顺序执行。因此,以上代码的最后一行可能会在匿名函数之前执行。

要解决此问题,您将需要触发任何依赖Shapefile于其回调内响应的代码:

for (var i = 0; i < SHP_files.length; i++) {
    shapefile = new Shapefile({
        shp: "shp/polygon/"+SHP_files[i]+".shp",
        dbf: "shp/polygon/"+SHP_files[i]+".dbf",
        }, function(data) {
            polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
            polygon_layer.addTo(map);
            executeMoreCode();
        });
};

function executeMoreCode() {
    console.log(polygon_layer.getLayers()); // IS OK
}
Run Code Online (Sandbox Code Playgroud)