Returning multiple values ​​in javascript?

Is there a way to use some kind of out or ref parameter modifiers using C # with Javascript to do something like this:

 function myManyReturnFunction(number1, number2, out x, out y) { x = number1 * number2; y = number1 / number2; return true; } var height1, height2 = 0; var check = myManyReturnFunction(1,1, out height1, out hight2); 

I would also like to change the link to the variable. So yes, passing the argument by reference.

+8
javascript
source share
5 answers
 function myManyReturnFunction(number1, number2) { return { x: number1 * number2, y: number1 / number2 } } 

And you do not need the x and y parameters, just call:

 var result = myManyReturnFunction(6, 9); var x = result.x; var y = result.y; 
+18
source share

You can create an "object" ...

 function getObj(){ var objOut = new Object(); objOut.name = "Smith"; objOut.State = "Arkansas"; return objOut; } 
+3
source share

If you define the 'out' variables in the global scope outside, if your function can be reassigned inside the function with something like this:

 var height1 = 0, height2 = 0; function myManyReturnFunction(number1, number2) { height1 = number1 * number2; height2 = number1 / number2; return true; } var check = myManyReturnFunction(1,1); 

You can also create an object that can then be passed to your function, which can be changed inside the function as follows:

 var myValues = {} function setValues(num1, num2, vals) { vals.x = num1 * num2; vals.y = num1 / num2; return True; } setValues(1, 1, myValues); 
+3
source share

There are several ways to return multiple values ​​in JavaScript. You can always return multiple values ​​to an array:

 function f() { return [1, 2]; } 

And refer to them as follows:

 var ret = f(); document.write(ret[0]); // first return value 

But the syntax is much better in JavaScript 1.7 with the addition of a destructuring destination (if you are lucky enough to focus on an environment that guarantees its support (for example, the Firefox extension)):

 var a, b; [a, b] = f(); document.write("a is " + a + " b is " + b + "<br>\n"); 

Another option is to return an object literal containing your values:

 function f() { return { one: 1, two: 2 }; } 

Which can be accessed by name:

 var ret = f(); document.write(ret.one + ", " + ret.two); 

And, of course, you can do something really terrible, for example, change the global scope or even set the properties of the function itself:

 function f() { f.one = 1; f.two = 2; } f(); document.write(f.one + ", " + f.two); 

Read more (and the source of some of these examples):

https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment_(Merge_into_own_page.2fsection )

+2
source share

You can return non-primitive types:

 function blah() { return { name: 'john', age: 23 }; }; var x = blah(); 
0
source share

All Articles