javascript return value is always undefined

前端 未结 3 1831
名媛妹妹
名媛妹妹 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: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; });
    }
    

提交回复
热议问题