I have a function that receives an array of Strings. These are the names of variables I'm supposed to concat together.
Something like:
function createArray(varNames){
varNames.each( function(varName){
someArray = someArray.concat(varName.items);
});
}
createArray(["array1", "array2"]);
I don't know how to take a string and select the variable named after it. Any way of doing this in Javascript?
3 Answers 3
Depends of the scope where the variable was defined. If it was defined in the global scope (inside a browser) you could access it via the window object.
For example:
var arr1 = [1,2,3,4,5];
window['arr1']; // 1,2,3,4,5
Comments
try window[varName] - drop the .items
for example
function createArray(varNames,theScope){
theScope = theScope || window;
varNames.each( function(varName){
someArray = someArray.concat(theScope[varName]);
});
}
createArray(["array1", "array2"]);
if you have
var array1=[...];
var array2=[...];
or
createArray(["array1", "array2"],myScope);
if you have
var myScope = {
"array1":[...],
"array2":[...],
}
Comments
You can pass variables in an array rather than passing a string.