如何使用对象名称值访问数组?

时间:2013-03-02 13:26:39

标签: javascript arrays string

我想做什么

我试图通过将参数传递给基本上控制幻灯片放映的函数来访问多个数组。传递给函数的参数是name的{​​{1}}。这是我尝试访问的阵列之一。 <a href=#" name="rebounding" onclick="nextPlayer(this.name)"></a>

问题

当我将参数传递给更改图像的函数时,我使用var reboundingImgs = ['tyson_chandler.png', 'dwight_howard.png', 'zach_randolph.png', 'omer_asik.png', 'nikola_vucevic.png', 'joakim_noah.png'];而不是获取名为[index]的数组中的索引,我得到reboundingImgs[]中的字母。例如如果index为2并且传入的参数I是“反弹”,则string parameter将为“b”。我需要使用我传入的参数访问数组,以显示右数组中的正确图像(我有几个包含图像的数组,例如scoringImgs [],reboundingImgs [],assistsImgs []等)

这是我的代码

parameter + "Imgs"[index]

3 个答案:

答案 0 :(得分:3)

为什么不将正确的数组作为参数传递给函数?

nextPlayer(reboundingImgs);

然后只是:

typeStatStr[index];

无论如何,如果数组是某种全局变量(窗口范围?),那么你可以这样做:

window[typeStatStr + "Imgs"][index];

答案 1 :(得分:3)

创建一个对象,该对象具有您可以在给定阵列名称的情况下访问的属性:

var imgs = {};

imgs.rebounding = ['tyson_chandler.png', 'dwight_howard.png', 
                   'zach_randolph.png', 'omer_asik.png', 
                   'nikola_vucevic.png', 'joakim_noah.png'];

alert(imgs["rebounding"][0]); // tyson_chandler.png

答案 2 :(得分:2)

String只是类型字符数组,所以通过执行:"Imgs"[index];您正在访问“Imgs”数组的索引元素。例如"Imgs"[2] == 'g'

如果要访问数组Imgs的索引元素,那么你应该这样做:

Imgs[index]; //Without the quotes
相关问题