1

Is it possible to create a new Array, giving it the name of the content of a variable?

For example something like this:

var nameofarray = "array_name";
var ¿nameofarray? = new Array(); 

So that ¿nameofarray? gets the value of "array_name"?

Cœur
  • 37,241
  • 25
  • 195
  • 267
gines capote
  • 1,110
  • 1
  • 8
  • 12
  • 1
    This is a big code smell. Why do you want to do this? – Bojangles Jun 21 '13 at 22:35
  • http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name – musicnothing Jun 21 '13 at 22:36
  • `this[nameofarray] = new Array(); ` – adeneo Jun 21 '13 at 22:37
  • 1
    `this` will always refer to the object that a function is a method of, whatever that is, unless a different scope is set with `apply()`, `call()` etc. It doesn't really matter what `this` is, as long as we know it's available in the current scope and it's an object, we can use it, but yes, it could cause some strange behaviour if we don't keep close track of what `this` really is, or try accessing it in lower scopes, like we would with variables declared in higher scopes etc. – adeneo Jun 21 '13 at 23:09
  • I'm not sure why I want to do that. I'm having problems with an asynchronous call, so that the second call overrides the Array before the first call writes the output. So I want to have two arrays, and I thought giving different names to the arrays would be a good idea. Excuse me if I'm wrong. – gines capote Jun 21 '13 at 23:41

3 Answers3

4

Assuming you are in global scope (called window) so:

var nameofarray = "array_name";
window[nameofarray] = new Array(); 

Otherwise it's only posible on objects:

function a() {
    var nameofarray = "array_name";
    var obj = {};
    obj[nameofarray] = new Array(); 
}

You can also use eval. Which is used for evaluating a string to JavaScript code:

eval('var '+ nameofarray+'=new Array()');

This will work in local scopes as well, but I hardly ever recorment it to anyone.

You would maybe like to read: http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

In PHP and other languages, they are called variable variables. This might help: Javascript "Variable Variables": how to assign variable based on another variable?

Community
  • 1
  • 1
1

If nameofarray is declared in the global scope, you can use the window object:

window[nameofarray] = [];  // Use an array literal instead also
^^^^^^^^^^^^^^^^^^^

But you really shouldn't be doing this.

David G
  • 94,763
  • 41
  • 167
  • 253