簡體   English   中英

如何使用串聯(AS3)調用函數的變量

[英]How to call a variable of a function using concatenation (AS3)

我需要按照以下示例使用串聯訪問此函數內的變量:

public function movePlates():void
{
    var plate1:Plate;
    var plate2:Plate;
    var cont:uint = 0;

    for (var i:uint = 0; i < LAYER_PLATES.numChildren; i++)
    {
        var tempPlate:Plate = LAYER_PLATES.getChildAt(i) as Plate;

        if (tempPlate.selected)
        {
            cont ++;

            this["plate" + cont] = LAYER_PLATES.getChildAt(i) as Plate;
        }
    }
}

編輯:

public function testFunction():void
{
    var test1:Sprite = new Sprite();
    var test2:Sprite = new Sprite();
    var tempNumber:Number;
    this.addChild(test1);
    test1.x = 100;
    this.addChild(test2);
    test2.x = 200;

    for (var i:uint = 1; i <= 2; i++)
    {
        tempNumber += this["test" + i].x;
    }

    trace("tempNumber: " + tempNumber);
}

如果我運行這樣的代碼,則此行this [“ test” + i]返回該類的變量。 我需要局部變量,函數的變量。

如果未將plate0顯式定義為類成員變量,或者未將class定義為動態,則在第一步上訪問plate0循環將導致未找到錯誤。 如果LAYER_PLATES.numChildren大於3 plate3, plate4, plate5...也會發生相同的情況。

編輯:

感謝@Smolniy,他更正了我的答案plate0從未被訪問過,因為cont在第一次訪問前已遞增。 因此,正如他提到的,問題應該在plate3

您不會獲得帶有[]表示法的局部變量。 您的案子有很多解決方案。 您可以使用字典或getChildAt()函數:

function testFunction():void
{
    var dict = new Dictionary(true);
    var test1:Sprite = new Sprite();
    var test2:Sprite = new Sprite();
    var tempNumber:Number = 0;

    addChild(test1);
    dict[test1] = test1.x = 100;

    addChild(test2);
    dict[test2] = test2.x = 200;

    for (var s:* in dict)
    {
        tempNumber += s.x;
        //or tempNumber += dict[s];
    }

    trace("tempNumber: " + tempNumber);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM