Javascript는 변수를 개체 이름으로 사용
변수 값을 사용하여 개체에 액세스하고 싶습니다.
myobject라는 개체가 있다고 가정 해 보겠습니다.
이 이름으로 변수를 채우고 변수를 사용하여 개체에 액세스하고 싶습니다.
예:
var objname = 'myobject';
{objname}.value = 'value';
글로벌 :
myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;
console.log(this[anObjectName]);
글로벌 : v2
var anObjectName = "myObject";
this[anObjectName] = "myvalue"
console.log(myObject)
로컬 : 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);
})();
로컬 : v2
(function() {
var scope = this;
scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;
console.log(scope.myObject.value);
}).call({});
변수 이름 주위에 대괄호를 사용하십시오.
var objname = 'myobject';
{[objname]}.value = 'value';
개체는 일부 범위에 있으므로 거의 항상 다음 구문을 통해 변수에 액세스 할 수 있습니다.
var objname = "myobject";
containing_scope_reference[objname].some_property = 'some value';
이것이 까다로워지는 유일한 곳은 닫힌 범위에 있고 최상위 지역 변수에 액세스하려는 경우입니다. 다음과 같은 경우 :
(function(){
var some_variable = {value: 25};
var x = "some_variable";
console.log(this[x], window[x]); // Doesn't work
})();
당신은 할 수 사용하여 해당 이겨내는 eval현재 범위 체인에 액세스하는 대신에 ...하지만 당신이 테스트의 많은 일을했습니다 당신이하지 않으면 내가하지 않는 것이 좋습니다 알고 그 일에 대해 갈 수있는 가장 좋은 방법입니다 것을.
(function(){
var some_variable = {value: 25};
var x = "some_variable";
eval(x).value = 42;
console.log(some_variable); // Works
})();
Your best bet is to have a reference to a name in an always-going-to-be-there object (like this in the global scope or a private top-level variable in a local scope) and put everything else in there.
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]
})();
Is it a global variable? If so, these are actually part of the window object, so you can do window[objname].value.
If it's local to a function, I don't think there's a good way to do what you want.
You can't do this in general, except at the window scope, where you can write window[objname].value = 'value';
You could use eval:
eval(variablename + ".value = 'value'");
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.
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.
function doIt() {
var scope = {
MyProp: "Hello"
};
var name = "MyProp";
console.log(scope[name]);
}
See Javascript: interpret string as object reference?
When using the window[objname], please make sure the objname is global variables. Otherwise, will work sometime, and fail sometimes. window[objname].value.
If object is in some namespace ie. Company.Module.Components.Foo you can use this function:
CoffeeScript:
objByName: (name, context = window) ->
ns = name.split "."
func = context
for n, i in ns
func = func[n]
return func
Resulted 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
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];
var micro=[{'test':'hello'}];
var device = 'test';
console.log(micro[device]);
참고URL : https://stackoverflow.com/questions/6084858/javascript-use-variable-as-object-name
'Programing' 카테고리의 다른 글
| Visual Basic .NET에서 Char 리터럴을 어떻게 선언합니까? (0) | 2020.09.19 |
|---|---|
| auto_ptr이 더 이상 사용되지 않는 이유는 무엇입니까? (0) | 2020.09.19 |
| Git : 'git reset'후 커밋 메시지를 재사용 / 보존하는 방법은 무엇입니까? (0) | 2020.09.19 |
| rspec 3-클래스 메서드 스텁 (0) | 2020.09.19 |
| View.setVisibility (GONE)을 애니메이션하려면 어떻게합니까? (0) | 2020.09.19 |