How to save a reference to a variable in an array?

I am 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 the variable reference.

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 an array a reference to a variable?

+6
source share
3 answers

You can not. Javascript always jumps by value. And all this is an object; var stores a pointer, so it passes the value of the pointer.

If your name = "bar" must be inside the function, you will need to pass the entire array. Then the function will have to change it using array["reference"] = "bar" .

Btw, [] is an array literal. {} is an object literal. This array["reference"] works because the array is also an object, but the array must access the index based on 0. You probably want to use {} .

And foo["bar"] equivalent to foo.bar . A longer syntax is more useful if the key can be dynamic, for example, foo[bar] , and not quite with foo.bar (or if you want to use a minimizer such as the Google Closure Compiler).

+7
source

Put the object in an array:

 var name = {}; name.title = "foo"; var array = []; array["reference"] = name; name.title = "bar"; // now returns "bar" array["reference"].title; 
+7
source

Try pushing an object into an array and change the values ​​inside it.

 var ar = []; var obj = {value: 10}; ar[ar.length] = obj; obj.value = 12; alert(ar[0].value); 
+4
source

Source: https://habr.com/ru/post/887163/


All Articles