JavaScript 在内部函数中保留一个 var

javascript keeping a var within inner functions

本文关键字:一个 var 内部函数 保留 JavaScript      更新时间:2023-09-26

我正在制作一个基于网站的仪表板。 功能之一是显示所有客户的位置。 当我将它们放在地图上时,我似乎无法正确弹出。

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);
                            }
                        );
                }
            }
        }

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

这是一个闭包问题,要解决它,您必须将$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);
                            }
        );

}

循环后for i总是locationList.length - 1。尝试使用本地i添加 IIFE。例如,您可以通过将循环替换为locationList.forEach来解决for

问题
这是

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

解决方案:是将值分配给一个变量,并在成功回调中使用此变量。

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
             }
           );
   }
 }

让我知道这是否有帮助。

这是一个范围问题。您的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);
        });
    }
  }
}