双字符串变量名(Javascript)
我知道还有其他类似的问题,但我觉得它们似乎没有回答我的问题。我基本上希望创建动态变量名。让我举个例子:双字符串变量名(Javascript),javascript,jquery,Javascript,Jquery,我知道还有其他类似的问题,但我觉得它们似乎没有回答我的问题。我基本上希望创建动态变量名。让我举个例子: //Take the strings "new" and "variable" and make them into a variable. "new" + "variable" = "Hello World"; //So technically the variable name is "newvariable" and has the value "Hello World" 所以基本上它
//Take the strings "new" and "variable" and make them into a variable.
"new" + "variable" = "Hello World";
//So technically the variable name is "newvariable" and has the value "Hello World"
所以基本上它需要两个字符串,并将它们组合成一个变量名。我该怎么做呢
另外,这不是组合变量值,只是将名称写入数组或对象
var arr = {};
arr['new' + 'variable'] = 'Hello World';
然后
或
alert(arr.newvariable);
那么,要访问这个变量,我是否每次只需键入
window['newvariable']
?是的,但实际上将变量放入window
名称空间不是一个好主意。在这种情况下,最好创建一个新的vars[]
,然后使用vars['newvariable']
。是的,就是这样。基本上,将“newvariable”作为数组(或对象)键进行usnig(谢谢!)这就更好地解释了。为什么要创建一个空数组来附加任意属性?您可以只使用对象文字:var arr={}哦,我从来没有在网上找到过那个帖子,谢谢你!)
alert(arr.newvariable);