Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.

var name = "foo";
var array = [];

array["reference"] = name;

name = "bar";

// Still returns "foo" when I'd like it to return "bar."
array["reference"];

Is there a way to make the array refer to the variable?

like image 466
Steve Geluso Avatar asked May 03 '11 04:05

Steve Geluso


3 Answers

My solution to saving a reference is to pass a function instead:

If the variable you want to reference is called myTarget, then use:

myRef = function (newVal) {
    if (newVal != undefined) myTarget = newVal;
    return myTarget;
}

To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.

Helpfully, you can also assign this to an array element as well:

var myArray = [myRef];

Then use myArray[0]() to read and myArray[0](<new value>) to write.

Disclaimer: I've only tested this with a numerical target as that is my use case.

like image 85
yatt Avatar answered Oct 15 '22 21:10

yatt


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;
like image 34
Lars Blumberg Avatar answered Oct 15 '22 20:10

Lars Blumberg


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);
like image 22
Marty Avatar answered Oct 15 '22 19:10

Marty