2015-12-01 180 views
0

我定義了名爲「delka」和「sirka」的變量,我想在下面的函數中更改它們的值。顯然,我做錯了什麼,因爲當函數結束時,這些變量不會受到它的影響。爲什麼? Thx尋求答案。Javascript - 變量範圍

var sirka; 
var delka; 
var mestoNaLL = document.getElementById("mesto").value; 
var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ "address": mestoNaLL }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       sirka = results[0].geometry.location.lat(); 
       delka = results[0].geometry.location.lng();   
      } else { 
       alert("Chyba: " + status); 
      } 
     }); 

     //undefined, why? 
     alert(mestoNaLL + " " + sirka + " " + delka + " "); 

編輯

這裏也是同樣的問題,對不對?

//works fine 
alert(markers[index].title + " " + infoWindows[index].content); 

        markers[index].addListener("click", function() { 

         //error - undefined 
         alert(markers[index].title + " " + infoWindows[index].content); 

         infoWindows[index].open(map, markers[index]); 
         map.setZoom(14); 
         map.setCenter(markers[index].getPosition());    
        }); 
+0

由於地理編碼方法是做異步東西:http://stackoverflow.com/questions/14220321/how-do -i-return-the-an-asynchronous-call/14220323#14220323 –

回答

0

以下代碼是asynchronous code。這意味着,它並不像其他的一樣被執行。在執行該代碼之前,您的警報將被執行,從而給您未定義的代碼。

geocoder.geocode({ "address": mestoNaLL }, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     sirka = results[0].geometry.location.lat(); 
     delka = results[0].geometry.location.lng();   
    } else { 
     alert("Chyba: " + status); 
    } 
}); 

溶液是採取alert內的OK

geocoder.geocode({ "address": mestoNaLL }, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     sirka = results[0].geometry.location.lat(); 
     delka = results[0].geometry.location.lng();   
     alert(mestoNaLL + " " + sirka + " " + delka + " "); 
    } else { 
     alert("Chyba: " + status); 
    } 
}); 
+0

謝謝,但是如果我需要變量從該函數獲取值,因爲我必須在使用它們之後?我真的不在乎警報,它只是測試信息。 – Tom

+0

@Tom這是不可能的,你需要改變你的代碼的工作方式。你需要將你的代碼分解成幾部分。第一部分調用地理編碼,第二部分在響應返回時運行。 – epascarello

+0

異步代碼不能以這種方式表現@Tom。抱歉。 –