0
var array1  = new Array(4);
var array2  = new Array(4);
var array3  = new Array(4);
var array4  = new Array(4);
var array5  = new Array(4);
var array6  = new Array(4);
var array7  = new Array(4);

for(var a = 1; a < 8; a++){
    array+ a = new Array(4);
}

I want to make an array with a for loop, but the variables has to be diffrent every time. So my question if this is possible, and if it is, how?

  • 6
    Why not use Multidimensional array/objects? – Justinas Apr 17 '15 at 12:25
  • 1
    Duplicate : [http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript](http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – jmgross Apr 17 '15 at 12:27
  • Wow, that was really silly of me, I was stuck on this for like an hour. Thanks for responding so quick! – Twan Korthout Apr 17 '15 at 12:28

2 Answers2

2

No you can't (not unless you use Eval() which you shouldn't...).

As Justinas has commented, you could use a Multidimensional array.

var array = [];
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));

for(var a = 1; a < 8; a++){
    array[a] = new Array(4);
}
Curtis
  • 101,612
  • 66
  • 270
  • 352
  • `eval()` surely, or is that to stop people using it by copy/pasting it without stopping to think about what they're doing :) – James Thorpe Apr 17 '15 at 12:29
  • @JamesThorpe I just avoid it like the plague. It's much harder to debug eval statements, and they're prone to security risk. Later down the line the application might be changed to start using user input for the value rather than `new Array(4)` without taking into account `eval()`. It's just best to avoid it whenever you can. – Curtis Apr 17 '15 at 12:31
  • Oh, I completely agree - I was just making a (bad) joke about the casing of it in your answer :) – James Thorpe Apr 17 '15 at 12:32
  • @JamesThorpe Ah! :) I completely missed that, makes a lot more sense when I read it back now haha – Curtis Apr 17 '15 at 12:33
0

You can do like so:

var myArrays = {};
myArrays["arrA"] = new Array(5);
myArrays["anotherArr"] = new Array(8);
...
Galman33
  • 154
  • 3