How can I store reference to a variable within an array?

Put an object into the array instead:

var name = {};
name.title = "foo";

var array = [];

array["reference"] = name;

name.title = "bar";

// now returns "bar"
array["reference"].title;

Try pushing an object to the array instead and altering values within it.

var ar = [];

var obj = {value: 10};
ar[ar.length] = obj;

obj.value = 12;

alert(ar[0].value);

You can't.

JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.

If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".

Btw, [] is an array literal. {} is an object literal. That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.

And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).

Tags:

Javascript