Javascript 连接字符串和变量以获取变量
我希望能够将字符串传递到函数中,用一个公共后缀连接它,并将新字符串用作现有变量。比如说,Javascript 连接字符串和变量以获取变量,javascript,jquery,Javascript,Jquery,我希望能够将字符串传递到函数中,用一个公共后缀连接它,并将新字符串用作现有变量。比如说, var firstInfo = "The first string says this."; var secondInfo = "The second says that."; updateInfo(arg) { console.log(arg + "Info"); } updateInfo("first"); /* Should print "The first string says th
var firstInfo = "The first string says this.";
var secondInfo = "The second says that.";
updateInfo(arg)
{
console.log(arg + "Info");
}
updateInfo("first");
/* Should print "The first string says this.", but instead does nothing. */
我做错了什么?这是纯javascript,但我对其他库持开放态度 应该是
updateInfo(arg)
{
firstInfo = arg + "Info";
console.log(firstInfo );
}
updateInfo(firstInfo );
您需要使用窗口[arg+Info]获取全局变量的值:
console.log(window[arg + "Info"]);
这里是一个完整的使用javascript函数eval,下面是
firstInfo变量在全局范围中定义,因此附加到窗口对象。 如果在没有窗口引用的函数范围内对其进行控制台操作,则将使用本地范围调用它 试试这个,我用过窗口对象
var firstInfo = "The first string says this.";
var secondInfo = "The second says that.";
function updateInfo(arg)
{
console.log(window[arg + "Info"]);
}
updateInfo("first");
以前,当我读到有关eval的文章时,它的口碑太差了,我不想尝试。但在这种情况下,你已经证明它是正确的解决方案。
var firstInfo = "The first string says this.";
var secondInfo = "The second says that.";
function updateInfo(arg)
{
console.log(window[arg + "Info"]);
}
updateInfo("first");