开发者

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

I'm trying to create an array that maps strings to variables. It seems that the array stores the current value 开发者_StackOverflow中文版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?


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;


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).


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);


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.


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(value_to_set);.

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

var myArray = [myRef];

Then use myArray0 to read and myArray[0](value_to_set) to write.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜