Skip to content

AS3: Passing an array into a function using the …rest parameter

… (rest) parameter 함수가 쉼표로 구분된 인수를 무제한으로 받도록 지정합니다.

라는 키워드가 있습니다. 위의 설명 처럼 인자의 갯수가 정해져 있지 않을때 사용하며 보통 함수에서 Array 로 반환되어 사용 합니다. 그런데 만약 쉼표로 구분된 인수를 사용하지 않고 바로 Array 를 넣으면 어떻게 될까요?

function myFunction(... rest):void {
   trace(rest.length + ": " + rest);
   trace(rest[2]);
}
var myArray:Array = new Array("this","is","my", "list", "of", "arguments");
myFunction(myArray);
/*
OUTPUTS:
1: this,is,my,list,of,arguments
undefined
*/

위의 예제 처럼 Array 자체를 인수의 하나로 인식 하기 때문에 그냥 Array 하나 입니다. 하지만 가끔은 꼭 Array 로 인수들을 넘겨 주고 싶을때 가 있습니다. 그런 경우에는 아래의 예제 처럼 apply 로 함수를 실행 시켜주면 되는군요.

function myFunction(... rest):void {
   trace(rest.length + ": " + rest);
   trace(rest[2]);
}
var myArray:Array = new Array("this","is","my", "list", "of", "arguments");
myFunction.apply(this, myArray);
/*
OUTPUTS:
6: this,is,my,list,of,arguments
my
*/

아래 와 같이 응용 할 수 있습니다.

function callExternalInterface($func:String, $params:Array):void
{
   $params.unshift($func);
   ExternalInterface.call.apply( $params );
}

출처 : http://blog.mandalatv.net/2009/04/as3-passing-an-array-into-a-function-using-the-rest-parameter/

4 thoughts on “AS3: Passing an array into a function using the …rest parameter”

  1. 하지만 실제 상황은 둘다 보내고 싶을때가 많다는거에요.
    인자로 보낸 모든 녀석을 전부 visible false로 해주는 함수가 있다고 해봐요.
    visibleFalse( getGroup1(), child1, menuItems )
    요개 현실이죠. 배열과 그냥 요소가 같이 날아가요.
    따라서 해결방법은 apply가 아니라 arrayStrip을 구현하는거죠.
    arrayStrip( [a,4,7], 6 ) = [a,4,7,6]
    이 함수를 구현하셔서 rest사용함수 내부에 배치하세요.
    function visibleFalse( …param ):void{
    param = arrayStrip( param );
    …,.

    1. 호~ 분명 그런 케이스도 있을 수 있겠군요. 하지만 예와 같이 ExternalInterface.call 처럼 수정 할 수 없는 함수에 대해서는 apply 해야 되지 않을까요?

  2. ㅎㅎ 코드를 잘보세요. rest를 처리하는 이슈와 함수내부의 함수를 apply와 무관해요.
    external에 apply하기전에 rest를 strip하는건 무관한 이슈에요.

Leave a Reply to hika Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.