jQuery dynamically increment variable name inside a for-loop

29,389

Solution 1

It would be best to use an array for this:

var test = [];

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

Then you could access the values like this:

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

If you have really good reason to have named variables for each value, you can create them like this:

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

console.log(test1);

Solution 2

As Mat stated, you should be using arrays for this type of functionality:

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

You could craft variable names, using object["varname"] syntax. But it's _generally_ bad practice:

var varName;
for (var i = 0; i <= countProjects; i++) {
    varName = "test" + i.toString();
    this[varName] = $(otherVar).something();
}
console.log(test1);
Share:
29,389
Matthias O.
Author by

Matthias O.

Updated on July 09, 2022

Comments

  • Matthias O.
    Matthias O. almost 2 years

    is it possible to add i to a var inside a for-loop? in wrong syntax it would look like the code below

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

    Thanks!