2013-02-11 77 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),因爲數組中的每個項目都是對相應對象的引用。

相關問題