Home > Uncategorized > Can you pass …rest to another function?

Can you pass …rest to another function?

March 9th, 2006

ActionScript 3.0 has a special parameter declaration, that looks like this:

function myFunc(a:String, b:String, ...rest)
{
}

The language allows you to call a function with more parameters than are formally specified, and if the function specifies a “…rest” parameter, then the remaining parameters are available to it as an Array named “rest”.

That’s great, but what if you then want to pass those parameters along to another function myFunc2 that takes a variable number of parameters? If you just pass the rest array, or a slice of it, then that goes into myFunc2 as a single parameter of type Array.

The only workaround I can think of is to write code like this:

switch (rest.length)
{
  case 0:
    logger.log(level, msg);
    break;
  case 1:
    logger.log(level, msg, rest[0]);
    break;
  case 2:
    logger.log(level, msg, rest[0], rest[1]);
    break;
(etc)
}

Update: The answer is to use Function.apply(). In this case, it would be:

logger.log([level, msg].concat(rest));

Cool!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
Author: David Coletta Categories: Uncategorized Tags:
  1. November 1st, 2006 at 19:03 | #1

    thanks, this was useful. though i should mention that the example solution you finally gave doesn’t use Function.apply. it should be:

    logger.log.apply(null, [level, msg].concat(rest));

    assuming log is static

Comments are closed.