最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: find array by name - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked May 16, 2010 at 17:20 Kevin CarmodyKevin Carmody 2,3192 gold badges23 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

window['arr'+intNum]

so

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

评论列表(0)

  1. 暂无评论