0

Is there any way to create a variable, and add an ID to the end of the actual variable name?

I have a variable called 'gauge', used to create a new Gauge object:

var gauge = new Gauge(target).setOptions(opts);

I want to add an ID to the variable, so something like:

var gauge+id = new Gauge(target).setOptions(opts);

It's because I'm creating a number of these objects, and have a specific ID already for each one, which I want to attach to the gauge object if possible?

All my code for this function is below, if it gives you a better idea of what i need to do:

    function go(id, votes)
{

var val = $('#votes_'+id).text();

var target = document.getElementById('foo_'+id); // your canvas element

var gauge = new Gauge(target).setOptions(opts); // create sexy gauge!
gauge.maxValue = 100; // set max gauge value
gauge.animationSpeed = 20; // set animation speed (32 is default value)
var a=votes+0.5;
gauge.set(val); // set actual value
}

My main problem arises on the last line. It says gauge.set(val), and it only sets the last object, ignoring all the other ones...

Nelson
  • 49,283
  • 8
  • 68
  • 81
gray
  • 798
  • 18
  • 31

3 Answers3

3

You could do

window['gauge'+id] = new Gauge(target).setOptions(opts);

But it's generally better to use an array or an object acting as a map :

var gauges = {};
gauges[id] = new Gauge(target).setOptions(opts);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Why don't you just use an array, like this :

var gauge = []; //this needs be declared at global scope
gauge[id] = new Gauge(target).setOptions(opts);
Nelson
  • 49,283
  • 8
  • 68
  • 81
  • this seems to give me an error in netbeans: missing ; before statement..can't see where it is missing the ; – gray Nov 24 '12 at 16:51
  • thanks, it does work, but i still get the same problem with the function only updating the last element – gray Nov 24 '12 at 16:56
  • Remember to place `var gauge = [];` in the global scope, that is, outside of your function and at the root of your js file. – Nelson Nov 24 '12 at 17:01
  • it kindof works - I tried setting each gauge and only the last one sets..for example i set it like this: gauge[3].set(20); ...and it works for the last one, maybe there is something wrong with how all the other guages are created – gray Nov 24 '12 at 17:12
  • okay, i've got it now, it actually is working but there is something slightly wrong with the gauges...thanks for the help – gray Nov 24 '12 at 17:39
1

You have few possible solutions.

  1. Use eval() - Slow one
  2. Use key/val array - Best solution
  3. Create an object - Also good option, but it requires some planing

In your case option 2 is the best.

Here you can find more info.

Or an example:

 var counter = 1;
 eval("var btn" + counter + "=123;");
 alert(btn1);
Community
  • 1
  • 1
Gajotres
  • 57,309
  • 16
  • 102
  • 130