Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pointers / Parameters 1

Status
Not open for further replies.

skydive

Programmer
May 30, 2001
16
IE
Howdy All,

I would like to pass a variable from one function to another function, change this variable in the second function and when returned to the first function the value would have been changed here.

function f_main()
{
var i = 1;
var retVal = true;
..
retVal = f_sub_function(i);
alert("The Value Is : " + i);
..
}
function f_sub_function(iCnt)
{
..
iCnt = 37;
..
return true;
}

When I run this I would like the alert to show me a value = 37.
This is like a pointer in C, I have been trying it with no success however it did work for an array. I passed the name of the array from one function to another and was able to change the values of the array in the second function and the changed values would show up in the first function. Now, this is very similar to C as the name of an array is the address of an array. In C, to pass the address rather than the value, you would put an '&' beforehand. So effectively I am looking for the JavaScript equivalent of '&'

Thanks & Regards
Skydive
 
IMHO the only objects that pass by value - local scal. variables (sorry for dirty english)
u can pass a variable like a pointer (pass an address) thru special functions:

1) write

function scall(func)
//call "special" function
{
var sf=func;
for(var ii=1;ii<scall.arguments.length;ii++) {
rg=new RegExp(&quot;argv\\[&quot;+ii+&quot;\\]&quot;,&quot;g&quot;);
sf=sf.replace(rg,scall.arguments[ii]);
}
return sf;}

2) define &quot;special&quot; function itself:

var FUN=&quot;argv[1]++;argv[2]+=argv[1];&quot;



u c, that it is not a function, but a string, arguments written just like in C's main()

3)checkin it:

function test(){
var A=10;
var B=20;
//arguments passed like strings
eval(scall(FUN,&quot;A&quot;,&quot;B&quot;));
alert(&quot;A=&quot;+A+&quot; B=&quot;+B);
}

looks like it works.. but why bothering so much?

u culd (& i think it is the best way 2 do it) make objects from ur scalars

function Int(x){
this.v=x;
}

function inc(p){
p.v++;
}

function test(){
var A=new Int(10);
inc(A);
alert(A.v);
}

that is why it worked when u used array: array is an object..

that's da way..
regards, vic
regards, vic
 
Thanks Vic,

Excellent that works,

Blue Skies!
Skydive
smiletiniest.gif
 
yeah, i like it too; may be i shuld write faq on it?
but it is not so frequently asked question.. i'll do it anyway..
yeah, yeah..
glad i culd help u.. :) regards, vic
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top