2

I have some js arrays and I want to find the arrays by name. for example:

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

And access them like this:

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

arrName[0]; // equals 3

Is this possible?

Thanks, Kevin

2 Answers 2

5

It is possible but I would suggest you place these arrays as properties of an object, that makes it a lot easier

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

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

Properties of objects can be accessed both using the . operator and as named items using the ["propname"] notation.

Using eval or resorting to using the above trick on window is not advised.

Eval'ing is normally a sign of ill constructed code, and using window relies on window being the Variable Object of the global scope - this is not part of any spec and will not necessarily work across browsers.

Sign up to request clarification or add additional context in comments.

3 Comments

why is the window "trick" not advisable (I am sure all the major FW developers in the js world would like to know that)
Because you rely on window being the Variable Object of the global scope - this is not part of any spec and will not necessarily work across browsers.
If you're worried about window not being the global object, you can call a standalone function that just returns this. Of course, at that point, it would probably be better just to use your suggestion and put them in an object.
3
window['arr'+intNum]

so

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

2 Comments

It should be noted that this is not array access, it's object access. Not to mention this example only works if the arrays are in global scope.
I'm going to have to give this answer the tick as it was the method I used. Basically, I had arrays that were being generated in the document, so they were in global scope. Gotta give a nod to Sean Kinsey (and discussion) for a more robust solution, as well as helping me understand what I'm using. Thanks all.

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.