How a function return two values?

C

Cylix

Can javascript using pointer or pass variable by reference?

Or I need to using object or Array to return the two values?

Thanks a lot.
 
V

Vincent van Beveren

Hi Cylix,

JavaScript doesn't have pointers, only referencs and primitives. You can
return anything anyway you like:

return [a,b];

return {foo : 'bar',
bar : 'food'};

res = new Object();
res.foo = 'bar';
res.bar = 'foo';
return res;

There are lots of options. Veriable by reference though is not one of
them. You could however pass an object:

var vector {
x : 3;
y : 2;
}

double(vector);

function double(v) {
v.x *= 2;
v.y *= 2;
}

Good luck,
Vincent
 
L

Lasse Reichstein Nielsen

Cylix said:
Can javascript using pointer or pass variable by reference?

Not directly, but you can pass the reference to a mutable object to
hold a value:

function foo(x,yRef) {
yRef.value = x;
return x*2;
}

var ref = {};
var z = foo(2, ref)'
alert([z, ref.value]); // 4,2
Or I need to using object or Array to return the two values?

That's another possibility, and one I would prefer. If you really need
to return two values, do that, instead of sneaking one of the return
values out the back door :)

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top