[SOLVED] JS. Transfer a variable to a function

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

[SOLVED] JS. Transfer a variable to a function

Post by Gente »

Hi everyone.

Didn't expected it would be a problem but is. The question is how to transfer the variable to the function?
Or in other words what is the analog of

Code: Select all

function name(&$varname)
in JS?

I thought it's something like this

Code: Select all

function name(var varname)
but it returns missing formal parameter error.

Please share your experience if you met such situation.

Thanks.
Last edited by Gente on Tue Jul 24, 2007 8:43 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You don't need the "var" keyword.
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post by Gente »

This way the value will be transfer, not variable. OK, example:

Code: Select all

var i = 0;
function inc(a)
{
  a++;
}
inc(i);
alert(i);
Now it shows 0. I want 1.

Thanks.
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

How about this:

Code: Select all

var i = 0;
function inc()
{
  i++;

}
inc(i);
alert(i);
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post by Gente »

It was just example. I can not use global variables because I would run this function several time with different parameters.
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

Other way is using return i; :)
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post by Gente »

And if I have the couple of variables? :wink:
I think there should be the way to transfer variable.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

So, you want to pass the arguments to the function by address, not by value - well, as far as I know you can't.
JS function arguments are passed by value. Sorry :)

"... And if I have the couple of variables?
I think there should be the way to transfer variable. ..."

You may return an object or an array.
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post by Gente »

Yeah I'm already doing my code with array. Just want to verify if transferring by address is possible.

Thank you all.
Post Reply