1

说我想要这样的东西:

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";

我可以使用变量计数器来增加变量的名称,以便完全拥有不同的变量吗?

4

2 回答 2

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]);
于 2012-11-20T15:21:29.350 回答
1

您不应该为此使用不同的变量。试试数组:

var arr = [];
...
arr.push('my var');

或对象:

var ob = {};
...
ob[counter] = 'my var';
于 2012-11-20T15:19:50.797 回答