Javascript“变量变量”:如何根据另一个变量分配变量? [英] Javascript "Variable Variables": how to assign variable based on another variable?

查看:107
本文介绍了Javascript“变量变量”:如何根据另一个变量分配变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a set of global counter variables in Javascript:

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆