Javascript“变量变量":如何根据另一个变量分配变量? [英] Javascript "Variable Variables": how to assign variable based on another variable?
问题描述
我在 Javascript 中有一组全局计数器变量:
I have a set of global counter variables in Javascript:
var counter_0 = 0;
var counter_1 = 0;
var counter_2 = 0;
等
然后我有一个 Javascript 函数,它接受映射到这些全局计数器的索引"编号.在此函数中,我需要使用传递给函数的索引"值来读取和写入这些全局计数器.
I then have a Javascript function that accepts an 'index' number that maps to those global counters. Inside this function, I need to read and write to those global counters using the 'index' value passed to the function.
我希望它如何工作的示例,但当然根本不起作用:
Example of how I'd like it to work, but of course doesn't work at all:
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
}
}
我希望我想要完成的事情很清楚.如果不是,我会尽力澄清.谢谢.
I hope what I'm trying to accomplish is clear. If not I'll try to clarify. Thanks.
编辑说明:
我不是要增加计数器的名称,而是要增加计数器包含的值.
I'm not trying to increment the name of the counter, but rather the value the counter contains.
推荐答案
对我来说看起来像一个数组,还是我遗漏了什么?
Looks like an array to me, or am I missing something?
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 */
}
}
这篇关于Javascript“变量变量":如何根据另一个变量分配变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!