Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "Variable Variables": how to assign variable based on another variable?

I have a set of global counter variables in Javascript:

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

etc

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.

EDIT Clarification:

I'm not trying to increment the name of the counter, but rather the value the counter contains.

like image 944
Ian Avatar asked Nov 26 '22 23:11

Ian


2 Answers

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 */ 
   }
}
like image 125
KooiInc Avatar answered Dec 10 '22 01:12

KooiInc


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

Make sure that index really is an integer, otherwise mayhem could ensue.

Edit: Others have pointed out that you should use an array if you can. But if you are stuck with the named global variables then the above approach will work.

Edit: bobince points out that you can use the window object to access globals by name, and so deserves any credit for the following:

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

Other answers have said "don't use eval()", but not why. Here's an explanation from MDC:

Don't use eval!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

There are safe alternatives to eval() for common use-cases.

like image 42
Bennett McElwee Avatar answered Dec 10 '22 02:12

Bennett McElwee