在for循环内部将i加入变量中是否可行? 错误的语法如下所示:
for(i=1; i<=countProjects; i++){
var test + i = $(otherVar).something();
};
谢谢!
在for循环内部将i加入变量中是否可行? 错误的语法如下所示:
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);
console.log(window.test1);
),那么window["test"...]
只能在全局范围内访问。在我看来,你不应该假设它总是全局范围。 - joncys正如Mat所说,你应该使用数组来实现这种功能:
var projects = [];
for (var i = 0; i <= countProjects; i++) {
projects.push($(otherVar).something());
}
您可以使用object["varname"]
语法来编写变量名,但这通常是不好的做法:
var varName;
for (var i = 0; i <= countProjects; i++) {
varName = "test" + i.toString();
this[varName] = $(otherVar).something();
}
console.log(test1);
test
变量进行什么操作? - Software Engineer