2011-03-10 157 views
3

我的問題是這個問題的Flex的換位:傳遞參數

Can I pass an array as arguments to a method with variable arguments in Java?

也就是說,我有一些ActionScript代碼數組我需要將數組中索引的每個對象都傳遞給方法method(...arguments)

一些代碼,使其明確:

private function mainMethod():void{ 
    var myArray:Array = new Array("1", "2", "3"); 
    // Call calledMethod and give it "1", "2" and "3" as arguments 
} 

private function calledMethod(...arguments):void{ 
    for each (argument:Object in arguments) 
     trace(argument); 
} 

是否有某種方式做意見建議是什麼?

回答

10

通過檢查Function對象本身是可能的。調用應用()就可以將工作:

private function mainMethod():void 
{ 
    var myArray:Array = new Array("1", "2", "3"); 

    // call calledMethod() and pass each object in myArray individually 
    // and not as an array 
    calledMethod.apply(this, myArray); 
} 

private function calledMethod(... args):void 
{ 
    trace(args.length); // traces 3 
} 

欲瞭解更多信息,請http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()

+0

這是完美的,謝謝! – Dunaril

+0

美麗!幾天前,我自己也有這個確切的問題。 –

1

編譯器很難猜出你想要什麼,你想傳遞一個Array類型的參數還是要傳遞該數組的元素。編譯器採用假設一。

+0

請問有沒有辦法來規避呢? – Dunaril

0

的參數... args是一個對象的方法等待的。您可以傳遞多個元素或(在這種情況下)一個數組與參數。

例子:

function mainMethod():void 
{ 
    //Passing parameters as one object 
    calledMethod([1, 2, 3]); 

    //Passing parameters separately 
    calledMethod(1, 2, 3); 
} 

function calledMethod(...args):void 
{ 
    for each (var argument in args) 
    { 
     trace(argument); 
    } 
} 

mainMethod(); 

希望它能幫助, 羅布

+0

對不起,但它沒有幫助。我的問題特別解決了向數組中包含的對象傳遞這種方法的問題。這意味着你不能在方法調用中顯式的使用這些對象。 – Dunaril

+0

我的不好,對不起:) – robertp