开发者

Accessing array elements from the array name received as a String in Javascript?

开发者 https://www.devze.com 2023-03-06 13:46 出处:网络
I have a function that receives an array of Strings. These are the names of variables I\'m supposed to concat together.

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(var开发者_开发技巧Names){
  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?


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消