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?

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
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":[...],
}

Comments

0

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

Comments

Your Answer

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.