[Javascript] How do you return more than one values from a function ?
Paul Novitski
paul at novitskisoftware.com
Fri Jul 2 20:36:44 CDT 2004
At 04:31 PM 7/2/2004, dev at qroute.net wrote:
>Is byref allowed in JS ?
>
>function isValidEmail(emailStr, byref reason)
>{
> reason='abc'
> return false
> // is something like this possible
>}
Not the way you've shown, but your goal of modifying multiple variables
with a single function call is possible using other methods.
All arguments to JavaScript functions are passed by value; if a function
attempts to modify an argument, the variable passed by the calling script
is unchanged:
function CallingFunction()
{
var i = 5;
DoIt(i);
alert("i = " + i);
}
function DoIt(argI)
{
argI = 10;
}
Result: i = 5 (unchanged)
However, here are three ways you can get a function to modify multiple
values, perceivable by the calling script:
1) Declare global variables and pass them to a function that receives the
values but modifies the global variables:
// we're not inside a function, so these variables are global:
var globalI = 5;
var globalJ = 7;
ModifyGlobals(globalI, globalJ);
alert("globalI = " + globalI);
alert("globalJ = " + globalJ);
function ModifyGlobals(argI, argJ)
{
globalI = argI * 1234567;
globalJ = argJ - 2.3;
}
This has the appearance of modifying arguments passed by reference but
really doesn't.
2) Return an array of values. (I'm using named array members here, but
numerically indexed elements work the same.)
function CallingFunction()
{
var a = new Array();
a.flies = 3;
a.frogs = 5;
a = ChangeValues(a);
alert("flies = " + a.flies);
alert("frogs = " + a.frogs);
}
function ChangeValues(argArray)
{
argArray.flies = 23;
argArray.frogs = 11;
return argArray;
}
3) Similar to example 2 but using object constructor syntax, so that the
properties of the new object are globally visible:
function CallingFunction()
{
var oResult = new Venusian(3, 7);
alert("eyes = " + oResult.eyes);
alert("tentacles = " + oResult.tentacles);
}
function Venusian(argEyes, argTentacles)
{
this.eyes = argEyes * 3;
this.tentacles = argTentacles * 7;
}
Since a JavaScript array really is an object and can have named properties
(elements), there's probably no need to go beyond example 2) unless you do
need a new object with custom functions built in.
Regards,
Paul
More information about the Javascript
mailing list