4

I have the below array with values

Na = [8289,92198,820624,84225,55775,98679,76317,8621,75928]

What I am expecting is 9 variables to be created as there are 9 values in this array. These 9 variables have to be dynamically created, as the values in the array changes.

Below is what I tried, but no luck.

for (var i = 1; i < na.length; i++) {
    window["na"+i] = new nas();
}

logInfo("na7" + na7);
4
  • 1
    but why do you think you need to do this? Commented Jul 28, 2017 at 16:26
  • 4
    Store them in an object, creating n global variables is a horrible horrible methodology Commented Jul 28, 2017 at 16:26
  • 1
    @zzzzBov Classic XY Problem Commented Jul 28, 2017 at 16:27
  • is it possible what you're after are nine instances based on the data in the array, and not nine separate variable declarations? Commented Jul 28, 2017 at 16:27

1 Answer 1

12

Try like this,

var Na = [8289,92198,820624];
var [na1, na2, na3] = Na;
console.log(na1, na2, na3);

Edit:

var Na = [8289,92198,820624];
var variable_names = {};
for(var i = 0; i< Na.length; i++){
   variable_names['na_'+i] = Na[i];
}
//console.log(variable_names);
console.log(variable_names.na_0);
Sign up to request clarification or add additional context in comments.

2 Comments

what happens when there're N number of values in "na" array.based on the array length the variable names have to be created
This answer is very useful to directly get and directly list the results from array of Promises to variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.