JQuery dynamically increments a variable name inside a for-loop

Can I add to var inside a for loop? in the wrong syntax it will look like the code below

for(i=1; i<=countProjects; i++){ var test + i = $(otherVar).something(); }; 

Thanks!

+3
source share
2 answers

It is best to use an array for this:

 var test = []; for (i = 1; i <= countProjects; i++) { test[i] = $(otherVar).something(); }; 

Then you can access the following values:

 console.log(test[1]); console.log(test[2]); etc... 

If you have a good reason to have named variables for each value, you can create them as follows:

 for (i = 1; i <= countProjects; i++) { window["test" + i] = $(otherVar).something(); }; console.log(test1); 
+5
source

As Mat pointed out, you should use arrays for this type of function:

 var projects = []; for (var i = 0; i <= countProjects; i++) { projects.push($(otherVar).something()); } 

You can create variable names using the syntax object["varname"] . But this is usually bad practice:

 var varName; for (var i = 0; i <= countProjects; i++) { varName = "test" + i.toString(); this[varName] = $(otherVar).something(); } console.log(test1); 
+5
source

All Articles