Javascript使用变量作为对象名称 [英] Javascript use variable as object name

查看:158
本文介绍了Javascript使用变量作为对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Let's say I have an object named myobject.

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

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

示例:

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({});

这篇关于Javascript使用变量作为对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆