Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm having some difficulty creating a variable with another variable in jQuery. I don't know how to write the var side of the equation. Here's what I'm trying to create:

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

with the goal to creating:

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

and so on...

like image 905
user3717403 Avatar asked Dec 20 '25 01:12

user3717403


2 Answers

You could create an object to hold these values but not dynamic variables.

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

Or if you want to make global variables (which is not recommended), you could use window:

var $counter= 0;
$('.selector').each(function(){
   $counter += 1;
   window["newVariable-"+$counter] = ...
});
like image 53
xdazz Avatar answered Dec 22 '25 16:12

xdazz


As others have pointed out, using an {} with square bracket notation will simplify this task greatly.

Something like this:

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!

Now, if you needed to expose the variables in a global scope (yuck - but hey, sometimes you gotta) so you don't need to specify an object (myobj), you can use window with square bracket notation in your 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!

Finally, if you search the web deep enough, you'll find eval examples like this:

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

Hope this helps!

like image 37
Jack Avatar answered Dec 22 '25 15:12

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!