Can I pass a value out of a javascript function?
Can I pass a value out of a javascript function and back to the calling function, e.g.
function updateURL(url, name, param) {开发者_运维百科
url = url + "&" + name + "=" + param;
}
I want to update url and return the new value.
Is this possible?
What you're asking for is called "pass-by-reference". Javascript uses "pass-by-value" for the native types (int, string, etc)---other types are pass-by-reference. For your specific case, I can think of two ways to get what you want. The first is to require callers to pass in an array with a single element and modify that element:
function updateURL(url, name, param) {
url[0] = url[0] + "&" + name + "=" + param;
}
url = ['http://www.google.com/?'];
updateURL(url, 'foo', 'bar');
alert(url[0]);
The second method would be to use an attribute on an object:
function updateURL(url, name, param) {
url.url = url.url + "&" + name + "=" + param;
}
url = new Object();
url.url = 'http://www.google.com/?';
updateURL(url, 'foo', 'bar');
alert(url.url);
function parentFunction() {
var url = 'http://www.example.com?qs=1';
var name = 'foo';
var param= 'bar';
var newUrl = updateURL(url, name, param);
}
function updateURL(url, name, param) {
url = url + "&" + name + "=" + param;
return url;
}
var myUrl = updateUrl('url', 'name', 'param');
function updateURL(url, name, param) {
url = url + "&" + name + "=" + param;
return url;
}
精彩评论