Javascript Javascript使用变量作为对象名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6084858/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:09:35  来源:igfitidea点击:

Javascript use variable as object name

javascript

提问by PeeHaa

I want to use the value of a variable to access an object.

我想使用变量的值来访问对象。

Let's say I have an object named myobject.

假设我有一个名为 myobject 的对象。

I want to fill a variable with this name and use the variable to access the object.

我想用这个名称填充一个变量并使用该变量来访问该对象。

Example:

例子:

var objname = 'myobject';
{objname}.value = 'value';

回答by Shaz

Global:

全球的:

myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;

console.log(this[anObjectName]);

Global: v2

全球:v2

var anObjectName = "myObject";
this[anObjectName] = "myvalue"

console.log(myObject)

Local: v1

本地:v1

(function() {
    var scope = this;

    if (scope != arguments.callee) {
        arguments.callee.call(arguments.callee);
        return false;
    }

    scope.myObject = { value: 0 };
    scope.anObjectName = "myObject";
    scope[scope.anObjectName].value++;

    console.log(scope.myObject.value);
})();

Local: v2

本地:v2

(function() {  
    var scope = this;

    scope.myObject = { value: 0 };
    scope.anObjectName = "myObject";
    scope[scope.anObjectName].value++;

    console.log(scope.myObject.value);    
}).call({});

回答by Vaishali Venkatesan

Use square bracket around variable name.

在变量名周围使用方括号。

var objname = 'myobject';
{[objname]}.value = 'value';

回答by JW.

Is it a global variable? If so, these are actually part of the windowobject, so you can do window[objname].value.

它是一个全局变量吗?如果是这样,这些实际上是window对象的一部分,因此您可以执行window[objname].value.

If it's local to a function, I don't think there's a good way to do what you want.

如果它是函数的本地函数,我认为没有什么好方法可以做你想做的事。

回答by Sean Vieira

The object exists in some scope, so you can almost always access the variable via this syntax:

该对象存在于某个范围内,因此您几乎总是可以通过以下语法访问该变量:

var objname = "myobject";
containing_scope_reference[objname].some_property = 'some value';

The only place where this gets tricky is when you are in a closed scope and you want access to a top-level local variable. When you have something like this:

唯一棘手的地方是当您处于封闭范围内并且想要访问顶级局部变量时。当你有这样的事情时:

(function(){
    var some_variable = {value: 25};
    var x = "some_variable";
    console.log(this[x], window[x]); // Doesn't work
})();

You canget around that by using evalinstead to access the current scope chain ... but I don't recommend it unless you've done a lot of testing and you knowthat that's the best way to go about things.

可以通过使用eval代替访问当前作用域链来解决这个问题……但我不推荐它,除非您已经进行了大量测试并且您知道这是处理事情的最佳方式。

(function(){
    var some_variable = {value: 25};
    var x = "some_variable";
    eval(x).value = 42;
    console.log(some_variable); // Works
})();

Your bestbet is to have a reference to a name in an always-going-to-be-there object (like thisin the global scope or a private top-level variable in a local scope) and put everythingelse in there.

最好的办法是有一个始终要到待有物体(比如一个名字的引用this在全局范围内或在局部范围内的私人顶级变量),并把一切都在那里东西。

Thus:

因此:

var my_outer_variable = {};
var outer_pointer = 'my_outer_variable';
// Reach my_outer_variable with this[outer_pointer]
// or window[outer_pointer]

(function(){
    var my_inner_scope = {'my_inner_variable': {} };
    var inner_pointer = 'my_inner_variable';
    // Reach my_inner_variable by using
    // my_inner_scope[inner_pointer]
})();

回答by Midas

You could use eval:

你可以使用eval

eval(variablename + ".value = 'value'");

回答by Neil

You can't do this in general, except at the window scope, where you can write window[objname].value = 'value';

您一般不能这样做,除非在窗口范围内,您可以在其中编写 window[objname].value = 'value';

回答by Juan Mendes

I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.

我认为 Shaz 对局部变量的回答很难理解,尽管它适用于非递归函数。这是我认为更清楚的另一种方式(但这仍然是他的想法,完全相同的行为)。它也不是动态访问局部变量,只是局部变量的属性。

Essentially, it's using a global variable (attached to the function object)

本质上,它使用一个全局变量(附加到函数对象)

// Here's  a version of it that is more straight forward.
function doIt() {
    doIt.objname = {};
    var someObject = "objname";
    doIt[someObject].value = "value";    
    console.log(doIt.objname);
})();

Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.

这与创建全局来存储变量本质上是一样的,因此您可以将其作为属性访问。创建一个全局来做到这一点是一种黑客。

Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.

这是一个更简洁的 hack,它不创建全局变量,而是使用局部变量。

function doIt() {
  var scope = {
     MyProp: "Hello"
  };
  var name = "MyProp";
  console.log(scope[name]);
}

See Javascript: interpret string as object reference?

请参阅Javascript:将字符串解释为对象引用?

回答by lyon819

When using the window[objname], please make sure the objname is global variables. Otherwise, will work sometime, and fail sometimes. window[objname].value.

使用 window[objname] 时,请确保 objname 是全局变量。否则,有时会工作,有时会失败。窗口[对象名称].值。

回答by lyon819

If object is in some namespace ie. Company.Module.Components.Fooyou can use this function:

如果对象在某个命名空间中,即。Company.Module.Components.Foo您可以使用此功能:

CoffeeScript:

咖啡脚本:

objByName: (name, context = window) ->
    ns = name.split "."
    func = context
    for n, i in ns
        func = func[n]
    return func

Resulted Js:

结果 Js:

objByName: function(name, context) {
  var func, i, n, ns, _i, _len;
  if (context == null) {
    context = window;
  }
  ns = name.split(".");
  func = context;
  for (i = _i = 0, _len = ns.length; _i < _len; i = ++_i) {
    n = ns[i];
    func = func[n];
  }
  return func;
}

Then you can create a new object or do whatever. Note the parenthises through.

然后你可以创建一个新对象或做任何事情。注意括号。

var o = new (objByName('Company.Module.Components.Foo'))
objByName('some.deeply.nested.object').value

This idea is borrowed from similar question: How to execute a JavaScript function when I have its name as a string

这个想法来自类似的问题:How to execute a JavaScript function when I have its name as a string

回答by Mitch Parker

One of the challenges I had with the answers is that it assumed that the object was a single level. For example,

我在回答中遇到的挑战之一是它假设对象是单个级别。例如,

const testObj = { testKey: 'testValue' }
const refString = 'testKey';
const refObj = testObj[refString];

works fine, but

工作正常,但

const testObj = { testKey:
                  { level2Key: 'level2Value' }
                }
const refString = 'testKey.level2Key';
const refObj = testObj[refString];

does not work.

不起作用。

What I ended up doing was building a function to access multi-level objects:

我最终做的是构建一个函数来访问多级对象:

objVar(str) {
    let obj = this;
    const parts = str.split('.');
    for (let p of parts) {
        obj = obj[p];
    }
    return obj;
}

In the second scenario, then, I can pass the string to this function to get back the object I'm looking for:

在第二种情况下,我可以将字符串传递给此函数以取回我正在寻找的对象:

const testObj = { testKey:
                  { level2Key: 'level2Value' }
                }
const refString = 'testObj.testKey.level2Key';
const refObj = objVar[refString];