Javascript“variablesvariables”:如何基于另一个variables分配variables?

我在Javascript中有一组全局计数器variables:

var counter_0 = 0; var counter_1 = 0; var counter_2 = 0; 

等等

然后我有一个Javascript函数接受映射到这些全局计数器的“索引”号码。 在这个函数里面,我需要使用传递给函数的'index'值来读写这些全局计数器。

我希望如何工作的例子,但当然根本不起作用:

 function process(index) { // do some processing // if 'index' == 0, then this would be incrementing the counter_0 global variable ++counter_+index; if (counter_+index == 13) { // do other stuff } } 

我希望我所做的是明确的。 如果没有,我会尽力澄清。 谢谢。

编辑澄清:

我不是要增加柜台的名字,而是柜台的价值。

看起来像一个arrays给我,还是我错过了什么?

 var counters = [0,0,0]; function process(index) { ++counters[index]; /* or ++counters[index]+index, not sure what you want to do */ if (counters[index] === 13) { /* do stuff */ } } 

eval() javascript函数将允许你完成这个。 然而,它通常是皱眉。 你的问题没有明确排除数组。 数组一定会更适合您所描述的模式。

 function process(index) { // do some processing var counter; eval('counter = ++counter_'+index); if (counter == 13) { // do other stuff } } 

确保索引真的是一个整数,否则可能会引发混乱。

编辑 :其他人指出,你应该使用一个数组,如果可以的话。 但是,如果你坚持使用命名的全局variables,那么上述方法将起作用。

编辑 :bobince指出,你可以使用窗口对象来访问全局名称,所以值得所有功劳:

 function process(index) { // do some processing var counter = ++window['counter_' + index]; if (counter == 13) { // do other stuff } } 

其他答案都说“不要使用eval() ”,但不是为什么。 以下是MDC的解释:

不要使用eval!

eval()是一个危险的函数,它执行用调用者的权限传递的代码。 如果您运行的eval()string可能会受到恶意方的影响,您最终可能会在您的网页/扩展程序的权限下,在用户计算机上运行恶意代码。

对于常见的使用情况,eval()是安全的select。