javascript return value is always undefined

前端 未结 3 1829
名媛妹妹
名媛妹妹 2021-01-07 10:50

I\'m trying to retrieve the 2 attributes of seprated function and I debug there values before the end of the function and they have a value but the return value is alwas und

相关标签:
3条回答
  • 2021-01-07 11:30

    Cause you're not returning it from the main function, you're returning it from the embedded anonymous function which isn't doing anything with it. Do this:

    function STAAPlanlat(){
    var lat;
    var lan;
    alert ("the function");
    if (navigator.geolocation) {
        //we supposed to call the handlers of the expections 
        navigator.geolocation.watchPosition(function(position) {
            alert("show position ");
            //  x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;   
            lat=position.coords.latitude;
            lan=position.coords.longitude;  
    
            //x.innnerHTML=out
            alert(lat+"<"+lan);
        });
        return lan;
    }
    else
        alert("error");
    }
    
    0 讨论(0)
  • 2021-01-07 11:33

    You are returning in the anonymous function and this value is never assigned to anything. You can do what you want with a callback.

    // untested code, hope it works
    function STAAPlanlat(callback){
        alert ("the function");
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(function(position) {
                var lat=position.coords.latitude;
                var lan=position.coords.longitude;  
                callback(lat, lan);
            });
        }
        else{
            alert("error");
        }
    }
    

    And your test function...

    function test(){
        var out;
        STAAPlanlat(function(lat, lon) { out = lat; });
    }
    
    0 讨论(0)
  • 2021-01-07 11:41

    because function STAAPlanlat doesn't return any value. your anonymous function returns lan but it is asynchronous callback. add this before return lan;:

    document.getElementById("STAAPlanlat").value = "lan is" + lan;
    
    0 讨论(0)
提交回复
热议问题