/    Sign up×
Community /Pin to ProfileBookmark

setting by reference

Is there a way to do this php equivalent in javascript:

a=5;
b=&a;

b++;

alert(a) //6
alert(b) //6

I’d like to traverse a binary tree in javascript which isn’t really fond of binary trees.

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@Jeff_MottSep 20.2011 — Not directly. You'll have to wrap the value in an object, because objects are passed by reference.

<i>
</i>var a = {
value: 5
};

var b = a;

b.value++;

alert(a.value); // 6
alert(b.value); // 6
Copy linkTweet thisAlerts:
@oaishmauthorSep 20.2011 — Yes, I can see how this works in the trivial case. How if I want to traverse a tree

Something like
[CODE]var x={}
for (i=1;i<100;i++){
var g=g||x;
g[i]={};
g=&g[i]; // by reference to get one level down this is what I really want

}
[/CODE]


so by the end we'd have x={1:{2:{3:{4: etc.

So we can traverse wtih
[CODE]
var p = function (n){
r = n||x;
if(functiontotestifobject(r)){
for(var i in r){
var z = p(r[i]); //I don't know, something like this, obviously I concocted this
} else { return something}
}
[/CODE]


so that var l = p(); would make l equal something
Copy linkTweet thisAlerts:
@Jeff_MottSep 20.2011 — Yes, I can see how this works in the trivial case. How if I want to traverse a tree

Something like
[CODE]var x={}
for (i=1;i<100;i++){
var g=g||x;
g[i]={};
g=[color=red]&[/color]g[i]; // by reference to get one level down this is what I really want

}
[/CODE]


so by the end we'd have x={1:{2:{3:{4: etc.[/QUOTE]


Just remove the ampersand, and you'll have it.
Copy linkTweet thisAlerts:
@rnd_meSep 20.2011 — [CODE]a=[5];
b=a;
b[0]++;
alert(a);[/CODE]
Copy linkTweet thisAlerts:
@martingalehSep 23.2011 — we can have

a={1:a, 2:b} whatever

b=a

b=b[2]

c={a:4}

b=c

alert(a[2]['a']) //woudlnt' this show undefined because we would have liked to do

b=&b[2] to differentiate between when we set a pointer to point to something else or when we point to something else.
×

Success!

Help @oaishm spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...