是否可以将 i 添加到 for 循环中的 var? 在错误的语法中,它看起来像下面的代码
for(i=1; i<=countProjects; i++){
var test + i = $(otherVar).something();
};
谢谢!
最佳答案
最好为此使用数组:
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);
关于javascript - jQuery 在 for 循环中动态增加变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9870526/