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

后端 未结 5 1478
小蘑菇
小蘑菇 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: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).

提交回复
热议问题