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

后端 未结 5 1460
小蘑菇
小蘑菇 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:15

    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;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 21:27

    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);
    
    0 讨论(0)
  • 2020-12-17 21:30

    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.

    0 讨论(0)
  • 2020-12-17 21:39

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

    0 讨论(0)
提交回复
热议问题