在内部函数中保留var的JavaScript

lymnna71  于 2022-10-24  发布在  Java
关注(0)|答案(4)|浏览(126)

我正在做一个基于网站的 Jmeter 板。其中一项功能是显示所有客户的位置。当我把这些放在Map上时,我似乎无法正确显示弹出窗口。

function getCoordinates(locationList) {
            for (var i = 0; i < locationList.length; i++) {
                if (locationList[i].city != null) {
                    $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
                        .success(
                            function (data) {
                                var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
                                marker.bindPopup(locationList[i].customerName);
                            }
                        );
                }
            }
        }

当我使用此代码时,弹出窗口将只在每个弹出窗口中包含最后一个客户的名称。有人知道如何确保使用正确用户的属性吗?

dfddblmv

dfddblmv1#

这是一个闭包问题,要修复它,您必须将$http调用移到一个新函数中,如下所示。

function httpCall(locationList,i){
         $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
                        .success(
                            function (data) {
                                var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
                                marker.bindPopup(locationList[i].customerName);
                            }
        );

}
irlmq6kh

irlmq6kh2#

for循环之后,i始终为locationList.length - 1。试着用当地的i来增加生活。例如,可以通过将for循环替换为locationList.forEach来解决问题

1dkrff03

1dkrff033#

这是臭名昭著的循环问题。因为您只是定义函数,而不是在for循环结束时实际执行它,所以所有函数的索引i将具有相同的值。

**解决方案:**将值赋给一个变量,并在您的Success回调中使用该变量。

for (var i = 0; i < locationList.length; i++) {
   if (locationList[i].city != null) {    
   var currLocation = locationList[i]; // assign the data to a variable 
   $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
   .success(
            function (data) {
              var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
              marker.bindPopup(currLocation.customerName); // use the variable instead of the indexed lookup
             }
           );
   }
 }

如果这有帮助,请告诉我。

kiz8lqtg

kiz8lqtg4#

这是一个范围问题。您的i将被更新,稍后,当您单击弹出窗口时,它将读取i的最后一个值。
您应该将条件放在for函数中,该函数接受参数i

function getCoordinates(locationList) {
  for (var i = 0; i < locationList.length; i++) {
    conditionalGet(i);
  }
  function conditionalGet(i) {
    if (locationList[i].city != null) {
      $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
        .success(function (data) {
          var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
          marker.bindPopup(locationList[i].customerName);
        });
    }
  }
}

相关问题