2013-02-11 82 views
0

它似乎很容易,但我有点迷路... 我需要的是将计数器值添加到变量名称。如何正确添加计数器的值到变量名称

for (var i=0; i<8; i++){ 
    var upBt0; //this is the name in the first iteration 
    var upBt1; //this is the name in the second iteration 
    . 
    . 
    . 
    var upBt8; //this is the name in the last iteration 
} 

我该如何正确地做到这一点? 对不起,丹尼尔

编辑:

for (var i=0; i<8; i++) 
    { 
     this.upBt = "upBt"+i; 
     this.upBt = new PL_Button().init("upBarButton"+i); 
} 

我创建按钮...特别是8个按钮...... 后来,我需要访问每个按钮:

function(){ 
    this.upBt1; 
    this.upBt1; 
    this.upBt3; 
    this.upBt6; 
} 

希望解释得更好。

编辑2: 最后,我用类的辅助数组解决了它,我在每次迭代中推送每个对象。此数组中的每一项都是对每个对象的真实参考,所以更改了数组中的项目,也会在相应对象中进行更改... 希望已经解释得很清楚。

感谢您的帮助, 丹尼尔

+1

你为什么要这样做?它看起来像一个数组或对象是你所需要的。 – elclanrs 2013-02-11 09:49:39

+0

嗨elclanrs,因为我需要以后访问这些变量......真的,我会用this.upBt1,this.upBt2创建变量....有一个类的变量,我需要以后访问它们的值.. .thanks – 2013-02-11 09:51:02

+1

似乎这是不正确的做法,但你可以发布一些更多的代码?这看起来像一个XY问题... – elclanrs 2013-02-11 09:51:59

回答

0

你可以利用这一点,但它是丑陋的代码......

for (var i=0; i<8; i++){ 
    this["upBt" + i] = Object.create(null); 
} 
0

使用数组帮助我:

this._arrayButtons = {}; 
for (var i=0; i<8; i++) 
{ 
    this.upBt = new PL_Button().init("upBarButton"+i); 
    this.upBt.imgPath = "res/builder/"+upBarImgs[i]; 
     . 
     . 
     . 
    this._arrayButtons[i] = this.upBt; 
} 

后,在一个函数中,我可以访问变量的内容,如:

function refreshFrameAlpha(){ 
    this._arrayButtons[3].alpha = 125; 
    this._arrayButtons[5].alpha = 225; 
    . 
    . 
} 

以这种方式,我可以刷新对象的alpha(p.e),因为数组中的每个项目都是对相应对象的引用。

相关问题