为什么这个变量未定义或没有返回? [英] Why is this variable undefined or not returned?
本文介绍了为什么这个变量未定义或没有返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
I have the following code:
/*
* 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将正确的位置打印到控制台,但当我写这篇文章时:
the LatLng prints the correct location to the console, but when I write this:
var pos = stringToLatLng('New York');
console.log(pos);
我得到 undefined
返回。这是为什么?谢谢
I get undefined
back. Why is that? thanks
推荐答案
类似于这样的内容:
Something like this:
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);
});
在您的代码中,当您返回时,您实际上是从函数(结果,状态){ ..}函数,而不是stringToLatLng函数,正如在注释中说的那样,它是一个异步调用,所以你必须使用回调函数。
In your code, when you return, you are actually returning from the function(results, status){..} function, not the stringToLatLng function, as said in the comments its an asynchronous call, so you must use a callback.
这篇关于为什么这个变量未定义或没有返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文