我想使用变量的值来访问对象.
假设我有一个名为myobject的对象.
我想用这个名称填充变量并使用该变量来访问该对象.
例:
var objname = 'myobject';
{objname}.value = 'value';
Run Code Online (Sandbox Code Playgroud)
Sha*_*haz 118
全球:
myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;
console.log(this[anObjectName]);
Run Code Online (Sandbox Code Playgroud)
全球:v2
var anObjectName = "myObject";
this[anObjectName] = "myvalue"
console.log(myObject)
Run Code Online (Sandbox Code Playgroud)
本地: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);
})();
Run Code Online (Sandbox Code Playgroud)
当地:v2
(function() {
var scope = this;
scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;
console.log(scope.myObject.value);
}).call({});
Run Code Online (Sandbox Code Playgroud)
小智 19
在变量名称周围使用方括号.
var objname = 'myobject';
{[objname]}.value = 'value';
Run Code Online (Sandbox Code Playgroud)
它是一个全局变量吗?如果是这样,这些实际上是window对象的一部分,所以你可以这样做window[objname].value.
如果它是一个函数的本地,我认为没有一个好的方法来做你想要的.
该对象存在于某个范围内,因此您几乎总是可以通过以下语法访问该变量:
var objname = "myobject";
containing_scope_reference[objname].some_property = 'some value';
Run Code Online (Sandbox Code Playgroud)
这个变得棘手的唯一地方是当你处于封闭的范围内并且你想要访问顶级局部变量时.当你有这样的事情:
(function(){
var some_variable = {value: 25};
var x = "some_variable";
console.log(this[x], window[x]); // Doesn't work
})();
Run Code Online (Sandbox Code Playgroud)
你可以得到解决,通过使用eval替代访问当前作用域链...但我不建议这样做,除非你已经做了很多的测试,你知道那这就是去了解事情的最好方法.
(function(){
var some_variable = {value: 25};
var x = "some_variable";
eval(x).value = 42;
console.log(some_variable); // Works
})();
Run Code Online (Sandbox Code Playgroud)
你最好的办法是有一个名称的引用始终持续到待有物品(如this在全局范围内或在局部范围内的私人顶级变量),并把一切其他在那里.
从而:
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]
})();
Run Code Online (Sandbox Code Playgroud)
你可以使用eval:
eval(variablename + ".value = 'value'");
Run Code Online (Sandbox Code Playgroud)