Reputation: 267
Say I have the following variables
example1 = 1
example2 = 32
example3 = 3345
etc all the way to something big, like
example100 = 222
I want to append each number into a separate div, each div labelled:
<div class = "exam1"> </div>
<div class = "exam2"> </div>
etc all the way to exam100
How can I do this using a for loop?
for ( var i = 1; i < 100; i++ ) {
$(".exam"+i).empty();$(".age-"+i).append( **????** );
}
I just don't know how to add a number i onto the end of a variable so that it will work, any ideas?
Upvotes: 0
Views: 239
Reputation: 148110
You better use array
instead of variable
. Managing variables is quite difficut and unnecessary if almost all cases. Imagine if you want one hundred more then you will need to repeat the same excersie.
var arr = [1, 32, 3345 /* 100 elements */];
for ( var i = 1; i <= 100; i++ )
{
$(".exam"+i).empty();$(".age-"+i).append(arr[i-1]);
}
But you can do with variables as well,
for ( var i = 1; i < 100; i++ )
{
$(".exam"+i).empty();$(".age-"+i).append(window['example'+i]);
}
Upvotes: 2
Reputation: 27823
Assuming your variables have been defined in the window scope (usually that means globally), you can access them like this:
var example1 = 100;
var i=1;
var t = window['example' + i];
console.log(t); // 100
Also you should seriously consider changing your 100 variables to one array (as the first comment to your question suggests).
Upvotes: 1
Reputation: 1022
Try the following (also it isn't the best way to achieve what you need):
for ( var i = 1; i < 100; i++ ) {
$(".exam"+i).empty();$(".age-"+i).append( window['example' + i] );
}
Upvotes: 1