【问题标题】:Pass arguments from an array to an Actionscript method with ...(rest) argument使用 ...(rest) 参数将参数从数组传递到 Actionscript 方法
【发布时间】:2011-07-12 18:21:10
【问题描述】:

我的问题是这个问题的 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);
}

有什么方法可以按照评论的建议去做吗?

【问题讨论】:

    标签: actionscript methods arguments


    【解决方案1】:

    可以通过 Function 对象本身来实现。调用 apply() 就可以了:

    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()

    【讨论】:

    • 漂亮!几天前,我自己也遇到了这个问题。
    【解决方案2】:

    编译器很难猜出你想要什么,你想传递一个数组类型的参数还是传递那个数组的元素。编译器采用假设一。

    【讨论】:

    • 有没有办法绕过这个?
    【解决方案3】:

    ...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();
    

    希望对你有帮助, 抢

    【讨论】:

    • 对不起,但它没有帮助。我的问题专门解决了将数组中包含的对象传递给这种方法的问题。这意味着您不能在方法调用中显式这些对象。
    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 2021-08-17
    • 2012-10-27
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 2020-03-16
    相关资源
    最近更新 更多