gpt4 book ai didi

javascript - 为什么这个变量未定义或未返回?

转载 作者:行者123 更新时间:2023-12-02 19:21:44 25 4
gpt4 key购买 nike

我有以下代码:

/*
* converts a string to geolocation and returns it
*/

function stringToLatLng(string){
if(typeof string == "string"){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': string}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("LatLng: "+results[0].geometry.location);
return results[0].geometry.location;
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}

LatLng 将正确的位置打印到控制台,但是当我这样写时:

var pos = stringToLatLng('New York');
console.log(pos);

我得到未定义返回。这是为什么?谢谢

最佳答案

类似这样的:

function stringToLatLng(strloc, callback){
if(typeof string == "string"){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': strloc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback.call({}, results[0].geometry.location);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}

stringToLatLng('New York', function(pos){
console.log(pos);
});

在您的代码中,当您返回时,您实际上是从 function(results, status){..} 函数返回,而不是 stringToLatLng 函数,正如注释中所述,它是一个异步调用,因此您必须使用回调.

关于javascript - 为什么这个变量未定义或未返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12467690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com