javascript - 在javascript中使用字符串访问变量

标签 javascript variables

如果我有:

name.sub = function() {
    var sub = {};
    var placeholder = "test"
    var test = function() {
        return 42;
    };

    // Desired code would be here

    return sub;
};

我想使用占位符来访问变量,以便获得42

类似的东西 window["name"]["sub"][placeholder] 似乎正在寻找 name.sub.test。

我找到的唯一答案是它是否是一个全局变量。 使用 eval 是可行的,但我听说应该尽可能避免它。

placeholder = "test"; 
console.log(eval(placeholder + '()'))
// Would return 42

我的实际最终目标是拥有一个关联数组,其中:

console.log(array[placeholder]);
// Would return 42

如有任何帮助,我们将不胜感激。

<小时/>

这就是我最终为感兴趣的人使用的:

name.sub= function() {
    var sub = {};
    var placeholder = "test"
    var test = function() {
        return 42;

    var newObj = {};
    newObj["test"] = function() {test()}

    console.log(newObj[placeholder]())
    // Should return 42
    };

最佳答案

您无法从函数外部访问函数内部的变量。

相反,你可以这样做:

name.sub = function(placeholder) {
  var functions = {
    "test": function() {
      return 42;
    },
  };
  return functions[placeholder]();
};

name.sub("test"); // 42

我不确定这是否是您正在寻找的内容,但希望是。解释更多吗?

关于javascript - 在javascript中使用字符串访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616437/

相关文章:

javascript - 如何从 jquery 中的选择器字符串正确创建变量

javascript - 将 React 组件添加/注入(inject)到来自后端的纯 HTML 中

delphi - 访问存储在另一个单元Delphi中的数据

java - 在没有初始化器的情况下将局部变量声明为 final 并在 if 语句中分配

vb.net - 在 Visual Basic 中使用变量名

variables - 如何在 Lua 中声明一个变量而不将其初始化为 nil?

windows - 批处理文件: List Directory & File names to individual variables and display as selection menu

javascript - svg 附加文本元素 - 给我错误的宽度

javascript - 如何从 "Session"中的.html页面检查 `.NET`

javascript - UrlFetchApp 未定义