-2

I had an array in PHP

vars = array('Date','Name','Number');

Using the "vars" array I could create more arrays using the names in the list:

for($i = 0;  $i < count($vars); $i++){
 ${$vars[$i]} = "Something";
}

Now, I have an array in JavaScript and I want to do the same: create variables using a list' names in a loop. This variables are going to be arrays and I just can't use a common array for all the variables. What can I do?

I know it's possible to do "variable" variables in JavaScript:

var obj = {}
obj.foo = 42;

var bar = 'foo';
console.log(obj[bar]);

But I don't know how to use it in a loop from another array

Aleharu
  • 170
  • 1
  • 9
  • don't you know? ok. What's your question? – vp_arth Nov 24 '14 at 16:02
  • Why don't you just use Array? Most of the times dynamic name variables are not needed. – nacholibre Nov 24 '14 at 16:03
  • New variables are going to be arrays too. – Aleharu Nov 24 '14 at 16:03
  • @user3570805 So what? you can have array within another array, even if you'd be able to do the same as php, all these arrays would be placed in the `window` or `this` object depending on the context so basically the same.. – Yotam Omer Nov 24 '14 at 16:08
  • Okay, having looked again at your question, I may have closed it prematurely, but, to be sure, I'll ask: *what precisely are you trying to do?* – David Thomas Nov 24 '14 at 16:11
  • I'm sorry I wasn't being clear. I was trying to define different variables in a loop and I was taking the "new values" from PHP – Aleharu Nov 24 '14 at 16:21
  • I've reopened your question, but having read your comment I'm still not sure what exactly you want to do, or want help with. Think it through, and remember that you're explaining your situation, and needs and code, to people that have never seen it, or your approach, before. Be clear. – David Thomas Nov 24 '14 at 16:26

2 Answers2

1

You can use this in global context to set global variables.

$vars = ['Date','Name','Number'];
for(var $i = 0;  $i < $vars.length; $i++){
  this[$vars[$i]] = "Something";
}
vp_arth
  • 14,461
  • 4
  • 37
  • 66
0

Ok, I finally found a solution

variables = ["Name1", "Name2", "Name3"];

for (var i = 0; i < variables.length; i++){
  window[variables[i]] = new Object();
  window[variables[i]] = [1, 2, 3];   
}

document.write(Name1) // It shows 1 2 3;
Aleharu
  • 170
  • 1
  • 9