Javascript: Array name as string; Need it to reference the actual array [duplicate]

被刻印的时光 ゝ 提交于 2019-12-11 03:34:25

问题


I have to "get at" an array, but all I have is a string that matches the array name. Obviously this kind of thing won't work, but it shows what I'm trying to do:

var arrayname = new Array(1, 2, 3);
var array = 'arrayname';

Alert(array[0]);

Of course, the example above yeilds 'a' instead of 1, like I'd need.

The background is that I'm working with a Hyperion Business Intelligence dashboard, where which array used, is determined by a substring of the button's name that was used to call it.


回答1:


It's very simple.

var storage = {};
storage.arrayname = [1, 2, 3];
alert(storage["arrayname"].join(','));

Polluting the global namespace is strongly discouraged. I would strongly advise you to refrain from using the window object for this purpose. Read HERE for more details.




回答2:


Try using the window object to retrieve it if it is defined in the window context.

var array = window["arrayname"]



回答3:


You can use

array = window['arrayname'];


来源:https://stackoverflow.com/questions/16282045/javascript-array-name-as-string-need-it-to-reference-the-actual-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!