jQuery在for循环中动态增加变量名 [英] jQuery dynamically increment variable name inside a for-loop
本文介绍了jQuery在for循环中动态增加变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在for循环中将i添加到var?
在错误的语法中看起来像下面的代码
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();
};
谢谢!
推荐答案
最好使用数组:
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);
这篇关于jQuery在for循环中动态增加变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文