Javascript jQuery在for循环中动态递增变量名

Javascript jQuery在for循环中动态递增变量名,javascript,jquery,variables,for-loop,count,Javascript,Jquery,Variables,For Loop,Count,是否可以将i添加到for循环内的var? 在错误的语法中,它看起来像下面的代码 for(i=1; i<=countProjects; i++){ var test + i = $(otherVar).something(); }; 对于(i=1;i最好使用数组: var test = []; for (i = 1; i <= countProjects; i++) { test[i] = $(otherVar).something(); }; 如果您有很好的

是否可以将i添加到for循环内的var? 在错误的语法中,它看起来像下面的代码

for(i=1; i<=countProjects; i++){

    var test + i = $(otherVar).something();

};

对于(i=1;i最好使用数组:

var test = [];

for (i = 1; i <= countProjects; i++) {
    test[i] = $(otherVar).something();
};
如果您有很好的理由为每个值命名变量,您可以这样创建它们:

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

console.log(test1);
对于(i=1;i如上所述,您应该使用数组来实现这类功能:

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

你应该使用数组。他想增加变量名。这是个问题。请详细说明。增加变量,还是变量名?你想用
test
variable做什么?对不起,如果我不清楚,变量名。所以如果I==3,你会得到test1、test2和test3
window[“test”…]如果跟踪(
console.log(window.test1);
上未使用范围指示,则只能在全局范围内访问。
。您不应该假定它始终是全局范围,IMHO。
var varName;
for (var i = 0; i <= countProjects; i++) {
    varName = "test" + i.toString();
    this[varName] = $(otherVar).something();
}
console.log(test1);