2

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?

Tom van der Woerdt
30.1k7 gold badges76 silver badges105 bronze badges
asked May 18, 2011 at 11:37

3 Answers 3

1

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
answered May 18, 2011 at 11:41
Sign up to request clarification or add additional context in comments.

Comments

0

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":[...],
}
answered May 18, 2011 at 11:41

Comments

0

You can pass variables in an array rather than passing a string.

Mr47
2,6651 gold badge20 silver badges26 bronze badges
answered May 18, 2011 at 11:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.