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"?
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/
In PHP and other languages, they are called variable variables. This might help: Javascript "Variable Variables": how to assign variable based on another variable?
this[nameofarray] = new Array();thiswill always refer to the object that a function is a method of, whatever that is, unless a different scope is set withapply(),call()etc. It doesn't really matter whatthisis, 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 whatthisreally is, or try accessing it in lower scopes, like we would with variables declared in higher scopes etc.