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

后端 未结 5 1459
小蘑菇
小蘑菇 2020-12-17 20:58

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 variabl

5条回答
  •  时光说笑
    2020-12-17 21:22

    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.

提交回复
热议问题