开发者

javascript - how to combine a static value and a dynamic value to get the value of an existing string

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 do开发者_如何学Cing wrong?


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].


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]);
}


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.


If you trust the event source, you could do this:

alert(eval('a_'+id))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜