1

我不确定这是可能的,但是,有没有办法选择一个与字符串同名的对象,并在 .each 循环中使用它?

    var test = "myobj"; 

    var myobj = {"1" : "2", "2" : "3"};

    function testing(test){

         // If i do a console.log on the variale "test":
         console.log(test); // will show the string: "myobj"

         typeof(test); // is string

         // somehow select the object with the name myobj, and maybe iterate through it?
         jQuery.each(myobj, function(key, val){
            alert(val); // right now this will alert the actual letters: m y o b j
         });

    }
4

3 回答 3

2

您可以使用它们的字符串名称来处理对象属性,如下所示:

obj["property"]

在您的示例中,您创建test为全局,这是window(我假设您正在浏览器中测试它)的一个属性:

window[myobj]
于 2013-06-15T18:43:42.047 回答
1

如果变量是全局的

  var test = "myobj";
  var myobj = {"1" : "2", "2" : "3"};

  console.log(window[test]);

请记住,如果您将代码放在$(function() { ... }); wrapper thatvar test andvar myobj will not be global and therefore not available under thewindow` 对象中。

于 2013-06-15T18:50:37.337 回答
0

正如其他答案指出的那样,在您的示例中,window[test] 如果您的myObj变量是全局的,则可以使用。

但是,这不是您应该这样做的方式。大概您将拥有许多其他相关变量,例如myobj2,yetAnotherObj等。否则这样做没有多大意义。但是你不想用这些变量把你的全局命名空间弄得乱七八糟。

相反,创建一个包含所有其他变量的对象:

var myObjects = {
    myobj: {"1" : "2", "2" : "3"},
    myobj2: {"4" : "5", "6" : "7"},
    yetAnotherObj: {"8" : "9", "10" : "11"}
};

现在,给定您的test变量,其中包含这些对象之一的名称,您将使用:

myObjects[test]

这不仅避免了全局命名空间的混乱,而且即使myObjects其中包含的对象是局部变量而不是全局变量,它也可以工作。

于 2013-06-15T19:31:55.697 回答