0

Let's say I have an array with variable names:

var array = [a, b, c];

How can I assign a value to the variable names stored in this array? For example I want to assign a value of 5 to "a".

I managed to do this in Python by:

globals()[Array[0]]=value

I would like to achieve the same result in JavaScript.

Thanks a lot

Francesco
  • 111
  • 9
  • 1
    Unless the variables in the array assignment reference objects the resulting array doesn't hold any variables, only the values that were assigned to them. – pilchard Feb 18 '23 at 20:27
  • and [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – pilchard Feb 18 '23 at 20:28
  • "*I have an array with variable names*" - no you don't. You have an array of values, the values that these three variables held when the line was evaluated to initialise the array. – Bergi Feb 19 '23 at 01:31
  • "*I want to assign a value of 5 to "a".*" - then why not just write `a = 5;`? Variable names should not be dynamic. What is your use case? – Bergi Feb 19 '23 at 01:32
  • My case is that the items in the array are not fixed. I have more scripts, and different scripts have different values within the array – Francesco Feb 20 '23 at 06:22
  • Variable names must be fixed. So don't use them for items that are not fixed. What is the actual problem you are trying to solve by this? – Bergi Feb 20 '23 at 06:24
  • I am trying to automate the procedure of assigning values to variables coming from the user through a GUI in different scripts. My aim is to avoid repeating myself. So rather than repeating writing the piece of code to assign the values to the specific variables for each script for each variable, I would like to have the same piece of code to be called for all of my cases. So I would like to simply write the array with variable names and write a generic code to assign to variable name stored in position 1 in the array the value stored in position 1 of an array of inputs coming from the GUI. – Francesco Feb 20 '23 at 06:33
  • Use objects with properties instead of variables and arrays. You won't have to write any code for "assignments", just pass the object (a key-value map, like a Python dictionary) into the function as an argument and access the properties directly. Use destructuring if you don't like property access expressions. – Bergi Feb 20 '23 at 06:41

0 Answers0