如何从 JavaScript 函数中获取多个返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3581687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch multiple return values from a JavaScript function
提问by mahesh
I have JavaScript function call to changeMapLocationfunction where in it I want to return the variables latand long1. I have some problem in code to return those two variables and alert in function call.
我有 JavaScript 函数调用changeMapLocation函数,我想在其中返回变量lat和long1. 我在代码中遇到了一些问题来返回这两个变量并在函数调用中发出警报。
var sample = changeMapLocation(state);
alert(sample.lat1);
alert(sample.lat2);
function changeMapLocation(state) {
var addressval=state;
var address;
var url;
var googleUrl= "http://maps.google.com/maps/api/geocode/json?";
var sensor = "&sensor=false";
if(addressval != null && addressval !="" && addressval.length!=0) {
address = "address="+encodeURIComponent(addressval);
$.ajax({
url:googleUrl+address+sensor,
type:"POST",
dataType:"json",
success:function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
var lat = jsonObj.results[0].geometry.location.lat;
var long1 = jsonObj.results[0].geometry.location.lng;
alert(lat);
alert(long1);
//var latlng = new google.maps.LatLng(lat,long1);
//alert(latlng);
},
error:function(){alert("unable to conect to google server");}
});
}
return(lat1:lat,lat2:long1);
}
回答by Daniel Vassallo
You have a bigger problem in there. You are calling the asynchronous $.ajax()method, where its callback function will be called after your changeMapLocation()function returns, and therefore your function will not work as you are expecting. Follow the comments in the example below:
你那里有更大的问题。您正在调用异步$.ajax()方法,在您的changeMapLocation()函数返回后将调用其回调函数,因此您的函数将无法按预期工作。请按照以下示例中的注释进行操作:
function changeMapLocation(state) {
var lat;
var long1;
// Since the $.ajax() method is using the asynchronous XMLHttpRequest, it
// will not block execution, and will return immediately after it is called,
// without waiting for the server to respond.
$.ajax({
url: 'url-here',
type: 'POST',
success: function(longlatJson) {
// The code here will be executed only when the server returns
// a response to the ajax request. This may happen several
// milliseconds after $.ajax() is called.
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
lat = jsonObj.results[0].geometry.location.lat;
long1 = jsonObj.results[0].geometry.location.lng;
// Now lat and long1 are set, but it is too late. Our
// changeMapLocation() function will have already returned.
}
});
// This part will be reached before the server responds to the asynchronous
// request above. Therefore the changeMapLocation() function returns an
// object with two properties lat1 and lat2 with an undefined value.
return {lat1: lat, lat2: long1};
}
You should consider refactoring your code in such a way that the logic to handle the ajax response is in the successcallback. Example:
您应该考虑以这样一种方式重构您的代码,即处理 ajax 响应的逻辑在success回调中。例子:
function changeMapLocation(state) {
$.ajax({
url: 'url-here',
type: 'POST',
success: function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
var lat = jsonObj.results[0].geometry.location.lat;
var long1 = jsonObj.results[0].geometry.location.lng;
// Update your map location in here, or call a helper function that
// can handle it:
myGoogleMap.setCenter(new google.maps.LatLng(lat, long1));
}
});
}
Note that changeMapLocation()does not return anything anymore. It will simply change the map location on its own, when the server responds to the Ajax request.
请注意,changeMapLocation()不再返回任何内容。当服务器响应 Ajax 请求时,它会自行更改地图位置。
In addition note that your latand long1variables were enclosed in the scope of the successinner function, and couldn't be accessed from the outer function.
另外请注意,您的lat和long1变量被封闭在success内部函数的范围内,无法从外部函数访问。
回答by desau
Wrap them both up in a single object and return that object:
将它们都包装在一个对象中并返回该对象:
var result = {
lat:lat,
long:long1
}
return result;
Then, in your function call:
然后,在您的函数调用中:
var result = functionName();
alert("lat: " + result.lat + "\n" + "long: " + result.long);
回答by Quentin
You can only return a single value. That value can be an object, but the syntax uses {}not ().
您只能返回一个值。该值可以是一个对象,但语法使用{}not ()。
And Asynchronous JavaScript and XML is Asynchronous. As far as the calling function is concerned, it is fire and forget, you don't get to return a value from it.
而异步 JavaScript 和 XML 是异步的。就调用函数而言,它是一劳永逸的,您无法从中返回值。
Your callback has to complete the task, it can't give the data backto something else to complete it.
您的回调必须完成任务,它不能将数据返回给其他东西来完成它。
回答by Daveo
Or the slightly longer version that is a little more readable
或者稍微长一点的版本,可读性更强
function getValues()
{
var r = {};
r.lat = 22;
r.lat2 = 33;
return r;
};
var x = getValues();
alert(x.lat);
alert(x.lat2);
回答by Marimuthu Madasamy
As noted in other answers, with asynchronous call, you will not get the values immediately after your Ajax call since ajax call would not have completed. so you are getting the values as undefined. You have two options:
正如其他答案中所述,使用异步调用,您不会在 Ajax 调用后立即获取值,因为 ajax 调用不会完成。所以你得到的值是未定义的。您有两个选择:
Option 1:
选项1:
Move the operations you do with the return values of ajax into the success callback function of ajax call. See jAndy's or Daniel Vassallo's answer.
将你对ajax的返回值所做的操作移到ajax调用的成功回调函数中。请参阅 jAndy 或 Daniel Vassallo 的回答。
Option 2:(async: false)
选项 2:(异步:假)
You can make the call to be synchronous by setting the option async: falsefor ajax()function. Then this method would block until the response is received and when it completes, you will have the values initialized through Ajax.
您可以拨打电话要通过设置选项同步async: false的AJAX()函数。然后此方法将阻塞,直到收到响应,当它完成时,您将通过 Ajax 初始化值。
with the second option, your code would look like:
使用第二个选项,您的代码将如下所示:
function changeMapLocation(state) {
// var addressval = $("#address").val();
var addressval=state;
var address;
var url;
var googleUrl= "http://maps.google.com/maps/api/geocode/json?";
var sensor = "&sensor=false";
var lat;
var long1;
if(addressval != null && addressval !="" && addressval.length!=0) {
address = "address="+encodeURIComponent(addressval);
$.ajax({
url:googleUrl+address+sensor,
type:"POST",
async: false,
dataType:"json",
success:function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
lat = jsonObj.results[0].geometry.location.lat;
long1 = jsonObj.results[0].geometry.location.lng;
alert(lat);
alert(long1);
//var latlng = new google.maps.LatLng(lat,long1);
//alert(latlng);
},
error:function(){alert("unable to conect to google server");}
});
}
return {lat1:lat,lat2:long1};
}
回答by jAndy
To return multiple values, you need to create an object.
要返回多个值,您需要创建一个对象。
return({
lat1: lat,
lat2: long1
});
Beside that, this code would not work either since $.ajax()creates an asychronousrequest, which fires later than your return statementdoes.
除此之外,此代码也不起作用,因为$.ajax()创建了一个异步请求,该请求比您的触发时间晚return statement。
So you need to invoke your own callback. like
所以你需要调用你自己的回调。喜欢
function changeMapLocation(state, cb){
$.ajax({
// much data
success: function(longlatJson) {
// do a lot of things
if(typeof cb === 'function')
cb.apply(null, [lat, long1]);
}
});
}
and then call it like
然后称之为
changeMapLocation("foobar", function(lat, long1){
alert(lat);
alert(long1);
});

