I'm sending a string as parameter to a function, but i already have a global variable in that name, i wa开发者_StackOverflownt to get the value of that variable but its sending as undefined..
My example code
i have a array as reg[0][0],reg[0][1],reg[1][0],reg[1][0],reg[2][0],reg[2][1]
and i have some global variables as tick1, tick2, tick3...
it will either have the values as 0,1 or 2
and in a function i called
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(eval("reg[id][1]")); // it should return the value of reg[0][1] if id is 0
}
But its not working.
The id wont be a numeral it will be string .. So how can i do this?
You shouldn't use eval for things like this. If you need to convert id
to a number, use the unary +
operator:
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(reg[+id][1]); // it should return the value of reg[0][1] if id is 0
}
or parseInt()
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(reg[parseInt(id, 10)][1]); // it should return the value of reg[0][1] if id is 0
}
If you need to parse a string like "tick1, tick2" then you have a few options. If the first part will always be "tick", you can slice the end off the string like so:
calc_score(id)
{
id = +id.slice(4); // or +id.substring(4) if you prefer
alert(reg[id][1]);
}
If tick1, tick2, tick3
are global variables, then instead of using eval()
, you should reference them via the window object like so:
calc_score(id) //id will return as either "tick1","tick2","tick3"
{
alert(window[id]);
}
Use this:
alert(reg[Number(id)][1]);
of course you should check that id
can be cast to a number before you do it. I don't really think you need the eval
, unless you are trying to do something else that you haven't mentioned.
Oh! You change the code like the following:
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(eval("reg[" + id + "][1]")); // it should return the value of reg[0][1] if id is 0
}
精彩评论