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.
-
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 */ } }
Ian : brilliant. exactly what i was missing. thanks. -
The
eval()
javascript function will allow you to accomplish this. However it's generally frowned upon. Your question didn't explicitly exclude arrays. Arrays would definitely be more appropriate for the pattern you've described. -
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.
bobince : Even if stuck with named vars you don't need and shouldn't use eval(). window['counter_'+index] will retrieve globals, just like any other attribute access.
0 comments:
Post a Comment