0

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?

2
  • 3
    why not use an array instead of 100 variables? one way would be: this["example" + i] Commented Oct 22, 2013 at 8:51
  • @Ghozt: If you have a textprocessor that can use Regular Expressions to replace text, you can easily replace your variables with an array. regex: /example(\d+)/ replace with example[$1]. Then, add an array declaration at the top of your JS var example = []; Commented Oct 22, 2013 at 8:57

3 Answers 3

2

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]);    
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.