AS3.0 ...args、...rest和arguments类

在操作数组的时候,会遇到这样的参数...args或...rest

查了下资料,摘录如下

...(rest)parameter 定义关键字

用法:

function functionName(parameter0, parameter1, ...rest){ 
    // statement(s) 
} 

 

指定函数将接受任意多个以逗号分隔的参数。参数列表成为了在整个函数体中可用的数组。在参数声明中,数组的名称在 ... 字符后指定。参数可以拥有保留字以外的任意名称。

如果与其它参数共同使用,则 ...(其余的)参数声明必须是最后指定的参数。只有传递给函数的参数数目超过其它参数的数目时,才会填充 ...(其余的)参数数组。

逗号分隔参数列表中的每一个参数都将放置在该数组的一个元素中。如果您传递了 Array 类的实例,则整个数组会放置到 ...(其余的)参数数组的单个元素中。

使用此参数会使 arguments 对象不可用。尽管 ...(其余的)参数提供了与 arguments 数组和 arguments.length 属性相同的功能,但是未提供与由 arguments.callee 提供的功能类似的功能。使用 ...(其余的)参数之前,请确保不需要使用 arguments.callee

例子:

package {
    import flash.display.MovieClip;
    
    public class RestParamExample extends MovieClip {
        public function RestParamExample() {
            traceParams(100, 130, "two"); // 100,130,two
            trace(average(4, 7, 13));     // 8
        }
    }
}


function traceParams(... rest) {
     trace(rest);
 }
 
function average(... args) : Number{
    var sum:Number = 0;
    for (var i:uint = 0; i < args.length; i++) {
        sum += args[i];
    }
    return (sum / args.length);
}

 

arguments类

public  class  arguments

用于存储和访问函数参数的参数对象。在一个函数体内,可以使用局部参数变量来访问其参数对象。

callee属性

public var callee:Function

对当前正在执行的函数的引用。

实例:

 package {
    import flash.display.Sprite;
    
    public class ArgumentsExample extends Sprite {
        private var count:int = 1;
        
        public function ArgumentsExample() {
            firstFunction(true);
        }

        public function firstFunction(callSecond:Boolean) {
            trace(count + ": firstFunction");
            if(callSecond) {
                secondFunction(arguments.callee);
            }
            else {
                trace("CALLS STOPPED");
            }
        }

        public function secondFunction(caller:Function) {
            trace(count + ": secondFunction\n");
            count++;
            caller(false);
        }        
    }
} 

 

 

posted @ 2012-12-19 20:25  sdlwlxf  阅读(995)  评论(0编辑  收藏  举报