4

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!

5
  • You should be using an array. Commented Mar 26, 2012 at 10:33
  • 3
    He wants to increment variable names. That's the question. Commented Mar 26, 2012 at 10:36
  • Please elaborate. Increment the variable, or the variable name? Commented Mar 26, 2012 at 10:37
  • What you want to do with test variable ? Commented Mar 26, 2012 at 10:38
  • sorry if I was unclear, the variable name. So if i == 3 you'll get test1, test2 and test3 Commented Mar 26, 2012 at 10:39

2 Answers 2

6

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

1 Comment

window["test"...] will only be accessible in global scope, if no scope indication is used on the trace (console.log(window.test1);. You shouldn't assume it's always global scope, IMHO.
5

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

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.