Javascript 按名称获取对象作为字符串而不使用eval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11924731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get object by name as string without eval
提问by Jeroen
The code below does what I want, but I would like to avoid eval
. Is there a function in Javascript that looks up an object by its name as defined by in a string?
下面的代码做了我想要的,但我想避免eval
. Javascript 中是否有一个函数可以通过字符串中定义的名称查找对象?
myobject = {"foo" : "bar"}
myname = "myobject";
eval(myname);
Some context: I am using this for an application in which a large number of nodes in the dom has a html5 data-object
attribute, which is used in the handler function to connect back to the model.
一些上下文:我将它用于一个应用程序,其中 dom 中的大量节点具有 html5data-object
属性,该属性在处理程序函数中用于连接回模型。
Edit: myobject is neither global nor local, it is defined in one of the parent frames of the handler.
编辑:myobject 既不是全局的也不是局部的,它是在处理程序的父框架之一中定义的。
回答by thecodeparadox
回答by jeff
Local Variable Solution:
局部变量解决方案:
You could make all objects that you want to access with a string properties of another object. For example:
您可以使用另一个对象的字符串属性创建要访问的所有对象。例如:
var objectHolder = {
myobject: {"foo" : "bar"},
myobject2: {"foo" : "bar"},
myobject3: {"foo" : "bar"}
};
And then access your desired object like this:
然后像这样访问你想要的对象:
var desiredObject = objectHolder["myobject"];
Global Variable Solution:
全局变量解决方案:
You can access global variables using a string like this:
您可以使用这样的字符串访问全局变量:
window["myobject"];
回答by SurlyP
This question is pretty old, but since it's the top result on Google for the query "javascript get object from string", I thought I'd share a technique for longer object paths using dot notation.
这个问题已经很老了,但由于它是 Google 上查询“javascript get object from string”的最高结果,我想我会分享一种使用点表示法获得更长对象路径的技术。
Given the following:
鉴于以下情况:
var foo = { 'bar': { 'alpha': 'beta' } };
We can get the value of 'alpha' from a string like this:
我们可以从这样的字符串中获取 'alpha' 的值:
var objPath = "bar.alpha";
var alphaVal = objPath.split('.')
.reduce(function (object, property) {
return object[property];
}, foo);
// alphaVal === "beta"
If it's global:
如果是全局的:
window.foo = { 'bar': { 'alpha': 'beta' } };
Just pass window
as the initialValue
for reduce
:
只需window
作为initialValue
for传递reduce
:
var objPath = "foo.bar.alpha";
var alphaVal = objPath.split('.')
.reduce(function (object, property) {
return object[property];
}, window);
// alphaVal === "beta"
Basically we can use reduce
to traverse object members by passing in the initial object as the initialValue
.
基本上我们可以reduce
通过将初始对象作为initialValue
.
回答by i--
since window is a global namespace, you could simply use
因为 window 是一个全局命名空间,你可以简单地使用
window[myname]