最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery dynamically increment variable name inside a for-loop - Stack Overflow

programmeradmin5浏览0评论

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!

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!

Share Improve this question edited Mar 26, 2012 at 10:40 Henrik Andersson 47.2k16 gold badges100 silver badges94 bronze badges asked Mar 26, 2012 at 10:32 Matthias O.Matthias O. 3121 gold badge4 silver badges13 bronze badges 5
  • You should be using an array. – Mat Commented Mar 26, 2012 at 10:33
  • 3 He wants to increment variable names. That's the question. – Henrik Andersson Commented Mar 26, 2012 at 10:36
  • Please elaborate. Increment the variable, or the variable name? – Jivings Commented Mar 26, 2012 at 10:37
  • What you want to do with test variable ? – Software Engineer 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 – Matthias O. Commented Mar 26, 2012 at 10:39
Add a ment  | 

2 Answers 2

Reset to default 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);

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);
发布评论

评论列表(0)

  1. 暂无评论