需要获取作为字符串发送的变量的值?

Vij*_*jay 1 javascript

我正在向函数发送一个字符串作为参数,但我已经在该名称中有一个全局变量,我想得到该变量的值,但它的发送为未定义的..

我的示例代码

我有一个数组如[0] [0],reg [0] [1],reg [1] [0],reg [1] [0],reg [2] [0],reg [2] [ 1]

我有一些全局变量,如tick1,tick2,tick3 ......

它的值为0,1或2

在我打电话的功能中

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

}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

id不会是数字它将是字符串..所以我该怎么做?

And*_*y E 6

不应该使用eval来做这样的事情.如果需要转换id为数字,请使用一元运算+符:

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 
} 
Run Code Online (Sandbox Code Playgroud)

要么 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 
} 
Run Code Online (Sandbox Code Playgroud)


如果您需要解析像"tick1,tick2"这样的字符串,那么您有几个选项.如果第一部分总是"tick",你可以像这样切掉字符串的结尾:

calc_score(id)
{
    id = +id.slice(4);         // or +id.substring(4) if you prefer
    alert(reg[id][1]); 
}
Run Code Online (Sandbox Code Playgroud)

如果tick1, tick2, tick3是全局变量,那么eval()您应该通过窗口对象引用它们,而不是使用它们,如下所示:

calc_score(id)   //id will return as either "tick1","tick2","tick3"
{
    alert(window[id]);
} 
Run Code Online (Sandbox Code Playgroud)