简体   繁体   中英

Get value of variable outside the function

I'm trying to get value of variable outside the function but I can't able to do so. Kindly give answers

<script>
    var lati;
    var lngi;   
    function getLocation() {
    if (navigator.geolocation) 
    {
      navigator.geolocation.getCurrentPosition(showPosition);
    } 
      initialize();
    }
    function showPosition(position) 
    {
      lati=position.coords.latitude;
      lngi=position.coords.longitude;  
    }
    alert(lati);
</script>

You do not get your value, because you are not calling getLocation() function. Because you are not calling it, it nevers change the value of lati and then it display it's default value which is undefined .

 // ------------------------ FUNCTIONS TO SIMULATE const navigator = { geolocation: { getCurrentPosition: (func) => { func({ coords: { latitude: '0.5125', longitude: '51.545', }, }); }, }, }; function initialize() { } // ------------------------ FUNCTIONS TO SIMULATE var lati; var lngi; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } initialize(); } function showPosition(position) { lati = position.coords.latitude; lngi = position.coords.longitude; } getLocation(); alert(lati);

In the snipped provided in the question, showPosition() is never called and, therefore, cannot modify the variable lati . If you call showPosition() before alert(lati) , it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM