0

Been researching this and really haven't found a solution. In JavaScript, I want to be able to save an array to another array that would contain the array name (savedArrayCreated) plus a number (1,2,3... etc.)

For example:

arrayCreated[]

Save the arrayCreated to: savedArrayCreated1

then go back and clear arrayCreated, populate it with new array numbers and:

Save the arrayCreated to: savedArrayCreated2

And so on.

So the number at the end of the savedArrayCreated field would increase and I would be able to create an array with that name/number combination.

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
  • 1
    Why would you want that? Arrays exist, so that you _don’t_ have to start using any such “numbered variable names” nonsense … You should go with `savedArrayCreated`, and make _that_ an array _of_ arrays. – misorude Aug 28 '19 at 12:08

3 Answers3

0

Well you can have something like this:

var arrayCreated = [1,2,3,4];
var dynamicName = 'savedArrayCreated1';

window[dynamicName] = [...arrayCreated]; //copy by val not ref
console.log(eval(dynamicName)); // print [1,2,3,4]
Elad
  • 891
  • 5
  • 15
0

I do not think you can create variables name in js. But I think the thing which you want to achieve you can do with array of arrays, which in my opinion is much better solution. Example:

savedArraysCreated = []
arrayCreated = [1, 2, 3]
saveArraysCreated[0] = arrayCreated

But also I suggest to check this post.

noname
  • 565
  • 6
  • 23
-1

You can assign dynamically named variables to the local scope:

for (var i = 0; i < 10; ++i) {
  var arrayCreated = [i+1,i+2,i+3]
   this["arrayCreatedSaved"+i] = arrayCreated;
}

var a = this.arrayCreatedSaved0;
var b = this.arrayCreatedSaved1;
console.log(a);
console.log(b);
MDBarbier
  • 379
  • 3
  • 12