【问题标题】:Creating a variable, with a variable in an each loop - jQuery创建一个变量,在每个循环中都有一个变量 - jQuery
【发布时间】:2014-08-03 13:40:24
【问题描述】:

我在用 jQuery 中的另一个变量创建变量时遇到了一些困难。我不知道如何写等式的 var 侧。这是我正在尝试创建的内容:

var $counter= 0;
    $('.selector').each(function(){
       $counter += 1;
       var newVariable-($counter) // this is where I'd like to create the new  
                                  // variable with the number from $counter at the end.
    });

以创造为目标:

newVariable-1
newVariable-2
newVariable-3... 

等等……

【问题讨论】:

标签: javascript jquery variables dynamic each


【解决方案1】:

您可以创建一个对象来保存这些值,但不能保存动态变量。

var $counter= 0;
var variableHolder = {};
$('.selector').each(function(){
   $counter += 1;
   variableHolder["newVariable-"+$counter] = ...
});

或者如果你想制作全局变量(不推荐),你可以使用window

var $counter= 0;
$('.selector').each(function(){
   $counter += 1;
   window["newVariable-"+$counter] = ...
});

【讨论】:

    【解决方案2】:

    正如其他人所指出的,将{}square bracket notation 一起使用将大大简化此任务。

    类似这样的:

    var myobj = {},
        prefix = 'my_cool_var';
    
    for(var i = 0, len = 10; i < len; i++) {
        myobj[prefix + i] = undefined; // { my_cool_var + i : undefined }
    }
    
    // Setters - dot notation and square bracket
    myobj.my_cool_var1 = "Hello!";
    myobj['my_cool_var2'] = "Hello 2!";
    
    // Getters - dot notation and square bracket
    alert(myobj.my_cool_var1); // alerts Hello!
    alert(myobj['my_cool_var2']); // alerts Hello 2!
    

    现在,如果您需要在全局范围内公开变量(糟糕,有时您必须这样做),这样您就不需要指定对象(myobj),您可以将 window 与 square for loop 中的括号符号。

    var prefix = 'my_global_var';
    
    for(var i = 0, len = 10; i < len; i++) {
        window[prefix + i] = undefined; // creates global, my_global_var + i = undefined
    }
    
    my_cool_var1 = "Hello!";
    alert(my_cool_var1); // alerts Hello!
    

    最后,如果你在网络上搜索得足够深,你会发现eval 这样的例子:

    var prefix = 'my_evil_var';
    
    for(var i = 0, len = 10; i < len; i++) {
        // Don't do this. Use square bracket notation with window, if you need a global.
        eval(prefix + i + '= undefined') // creates global, my_evil_var + i = undefined
    }
    
    my_evil_var = "Eval abuse is bad!!";
    alert(my_evil_var1); // alerts Eval abuse is bad!!
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      只要在这个上下文中使用 json,

      var $counter= 0;
      var $newVar = {};
      
      $('.selector').each(function(){
         $counter += 1;
         $newVar['newVariable-'+ ($counter)] = null;
      });
      

      这样您就可以像$newVar.newVariable-1,..$newVar.newVariable-N 一样访问它。请注意,这是最佳做法,我们可以按照您的要求访问窗口对象,但不建议这样做。

      【讨论】:

        猜你喜欢
        • 2011-10-22
        • 2019-08-21
        • 1970-01-01
        • 1970-01-01
        • 2018-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多