0

Is there any way to use the data from one variable in the declaration of another variable? It is the same concept of coercing strings, just in the variable declaration. For example, if I wanted to create a variable called user1, is there any way to do it somehow like this:

var i = 1; // Creates variable with value of 1
var user + i = "John"; // Creates variable with name of user1 (because i has a value of 1)
Aidan
  • 3
  • 2

2 Answers2

1

You can do something like

var i = 1;
var username = 'John';
var users = {};
users[username + i] = username

And after this you can use

users.John1 

Is this acceptable ?

Johan Willfred
  • 811
  • 7
  • 14
0
 var i = 1; // Creates variable with value of 1

Instead of var user + i = "John"; // Creates variable with name of user1 (because i has a value of 1) you should use:

 window['user'+i] ="John";

 alert(user1);

https://jsfiddle.net/6x0uLbe8/

Milaci
  • 515
  • 2
  • 7
  • 24