间接访问变量 [英] Accessing variables indirectly

查看:82
本文介绍了间接访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码(firefox扩展中的javascript)中,我有一些
变量的列表,如下所示:

Within my code (javascript in a firefox extension), i have a list of some variables, like this:

var myApp = {
 var1: true,
 var2: false,
 var3: true,
 var4: false
};

我想访问这些变量以使用
a函数间接获取它们的值:

I want to access these variables to get their value indirectly using a function:

var myApp = {
 var1: true,
 var2: false,
 var3: true,
 var4: false,

 varGetter: function(aName) {
  // code
  return myApp.aName.value;
 }
};

我将此函数称为例如:

if(myApp.varGetter("var2")) {alert("true")};

现在,如何实现此功能以实现我的目标?

Now, how this function can be implemented to do what i want?

推荐答案

问题是您正在尝试使用点表示法和变量访问属性。

The problem is that you are trying to access a property with the dot notation and the variable.

myApp.aName.value;

这有时会创建新属性或返回 undefined

this sometimes creates new property or returns undefined

你应该使用这种表示法

myApp[aName];

这篇关于间接访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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