创建一个变量,在每个循环中使用一个变量- jQuery

Creating a variable, with a variable in an each loop - jQuery

本文关键字:变量 一个 jQuery 创建 循环      更新时间:2023-09-26

我在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... 

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

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] = ...
});

正如其他人指出的那样,使用方括号符号的{}将大大简化此任务。

像这样:

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),您可以在for loop中使用window和方括号符号。

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!!

希望这对你有帮助!

在这种情况下使用json,

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

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