Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create variables from array values in Javascript

Tags:

javascript

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);
like image 459
shiv Avatar asked Oct 19 '25 13:10

shiv


1 Answers

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);
like image 108
Always Sunny Avatar answered Oct 21 '25 02:10

Always Sunny