Reputation: 2405
var a_0, a_1, a_2 = 0;
function onclick( id ) {
// id is either 0,1 or 2
// echos 'a_0', 'a_1' or 'a_2', but I need it to echo "0".
alert( 'a_' + id );
}
What am I doing wrong?
Upvotes: 1
Views: 2198
Reputation: 18288
instead of naming your vars a_0, a_1 etc, use an array
var a=[];
a[0]=a[1]=a[2]=0;
function onclick(id){
alert(a[id]);
}
Upvotes: 2
Reputation: 42496
Instead of declaring a_0
, a_1
, and a_2
as global variables, put them in an object:
var a_x = {
a_0: 0,
a_1: 0,
a_2: 0
}
Then you can access those properties like this: a_x["a_" + id]
.
Upvotes: 4
Reputation: 18495
If you trust the event source, you could do this:
alert(eval('a_'+id))
Upvotes: 0
Reputation: 548
You need to use eval()
alert(eval('a_'+id));
eval() isn't usually recommended, though, but it depends on what you're trying to achieve.
Upvotes: 1