jQuery dynamically increment variable name inside a for-loop

前端 未结 2 1581
温柔的废话
温柔的废话 2021-01-03 08:15

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 =         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 08:36

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

提交回复
热议问题