Javascript: find array by name

I have multiple js arrays and I want to search for arrays by name. eg:

arr1 = [1,2,3];
arr2 = [3,4,5];

      

And refer to them like this:

var intNum = 2;
var arrName = 'arr' + intNum;

arrName[0]; // equals 3

      

Is it possible?

Thanks, Kevin

+2


a source to share


2 answers


window['arr'+intNum]

      

So



arr1 = [1,2,3];
arr2 = [3,4,5];
intNum=2;
alert(window['arr'+intNum][1]); //will alert 4

      

+3


a source


Perhaps, but I suggest placing these arrays as properties of the object, which makes it much easier to work with

var arrays {
    arr1 : [1,2,3],
    arr2 : [4,5,6]
}

var arrNum = 2;
var arr = arrays["arr" + arrNum] // arrays.arr2

      

Object properties can be accessed using both operator .

and names using notation ["propname"]

.



Using eval

or using the above trick is window

not recommended.

Eval'ing is usually a sign of poorly designed code, and window usage relies on Window being a global scope Variable Object - this is not part of any specification and will not necessarily work in browsers.

+5


a source







All Articles