javascript - 字符串到真实对象
我有一个 javascript 对象 varflower_1; var Flower_2;
我的问题是我是否有另一个变量,例如字符串 var Name;
举例来说: Name = "flower_1";
如何我将 Name
变量更改为对象 "flower_1"
I have a javascript objects var flower_1; var flower_2;
My question is if I have another variable for example a String var Name;
And lets say for example: Name = "flower_1";
How can I change the Name
variable into an object "flower_1"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解你的问题,你会得到这样的结果:
你可以这样做,但如果可能的话应该避免这样做:
eval
是一个非常大的,而且很容易应该而且可以避免被滥用的工具。在几年的 JavaScript 开发中,我从未在生产代码中使用过它。另请注意,在新的“严格”模式中不允许使用eval
语言的(严格模式带来的众多改进之一)。在这种特殊情况下,很容易避免:
现在,
flower_1
和flower_2
是对象的属性,您可以使用括号表示法([]
) 和字符串名称来访问这些属性。这是因为在 JavaScript 对象中,您可以使用点符号和文字(例如,obj.foo
)访问属性,也可以使用括号符号和字符串(例如,obj[" foo"]
)。在第二种情况下,字符串不必是字符串文字,它可以是表达式的结果,包括(如本例中)从变量中检索字符串。这是两种技术的实例。
请注意,如果您的
var
语句是全局变量,那么这些变量成为全局对象的属性,在网络浏览器上是window
,因此如果它们是全局变量,您可以通过window[name]
访问它们代码> 出于完全相同的原因objects[name]
有效。但最佳实践是避免全局变量(如果可以的话,完全避免,或者仅公开一个具有良好唯一名称的变量,然后在必要时包含所有公共内容 - 例如,如果外部代码需要访问您的内容)。If I understand your question correctly, you have something like this:
You can do that, but it should be avoided if at all possible:
eval
is a very big, and easily abused tool which should be, and can be, avoided. I've never had to use it in production code in several years of JavaScript development. Also note thateval
is disallowed in the new "strict" mode of the language (one of many improvements strict mode brings).In this particular case, it's pretty easy to avoid:
Now,
flower_1
andflower_2
are properties of an object, and you can use bracketed notation ([]
) with a string name to access those properties. This is because in JavaScript objects, you can either access a property using dotted notation and a literal (e.g.,obj.foo
), or using bracketed notation and a string (e.g.,obj["foo"]
). In the second case, the string doesn't have to be a string literal, it can be the result of an expression, including (as in this case) retrieving the string from a variable.Here's a live example of both techniques.
Note that if your
var
statements are globals, then those vars become properties of the global object, which on web browsers iswindow
, so if they're globals you could access them viawindow[name]
for exactly the same reasonobjects[name]
works. But it's best practice to avoid global variables (entirely if you can, or exposing just one with a good unique name that then contains all of your public stuff if necessary — e.g., if external code needs to access your stuff).您可以使用
eval()
函数:值得注意的是,使用
eval()
函数并不是最佳实践,应不惜一切代价避免使用。更好的(也是更推荐的)解决方案是使用关联数组:
You can use the
eval()
function:It's worth noting though that use of the
eval()
function is not best practise, and should be avoided at all costs.A better (and much more recommended) solution would be to use an associative array: