说我想要这样的事情:
var i = 0;
for (i upto 100) {
var x+i = "This is another variable altogether";
i++;
}
javascript解释器会看到:
var x = "This is another variable altogether";
var x1 = "This is another variable altogether";
var x2= "This is another variable altogether";
var x3 = "This is another variable altogether";
var x4 = "This is another variable altogether";
我可以使用变量计数器来增加变量的名称,这样我就会有完全不同的变量吗?
答案 0 :(得分:7)
技术上,是的。
如果您在我怀疑的全球范围内开展业务,您可以这样做:
for (var i=0; i<100; i++){
window["x"+i]="This is another variable altogether";
}
console.log(x1);
但是你应该用数组做这种事情,所以:
var arr=[];
for (var i=0; i<100; i++){
arr[i]="This is another variable altogether";
}
console.log(arr[1]);
答案 1 :(得分:1)
您不应该使用不同的变量。尝试一下Array:
var arr = [];
...
arr.push('my var');
或对象:
var ob = {};
...
ob[counter] = 'my var';