Converting arguments to a Javascript Array

Inside of any function, the Javascript variable arguments is available to the programmer to use. arguments is an array-like object, but the standard array operators like splice do not work without some conversion.

This is the snippet to convert:

  ...
  var args = Array.prototype.slice.call( arguments, 0 );
  // use args here as a native Javascript array.
  ...

The reason I need this is that recently, I have had to create a sort of generic proxy pattern to interface with a Flash widget. The proxy calls Flash object functions only when the widget is ready. I am not fully convinced that the way I have implemented this is “good” and am wondering if there is a better way, if anyone has a suggestion, I’m open. To do the task, I had to convert the Javascript arguments object into a real array so that I could do some array manipulation.

My interface to the proxy is:

...
    callFlashFunction: function() {
        // The Flash function name to call.
        var funcName = arguments[ 0 ];

        // Convert arguments to an array.
        var args = Array.prototype.slice.call( arguments, 0 );

        // Remove funcName from the arguments list
        args.splice( 0, 1 );                                

        // Gets a reference to the flash object from an object member function.
        var flashObject = this.getFlashObject();   

        // Finally do the call with the correct arguments list.
        flashObject[ funcName ].apply( flashObject, args );
    },
...

The first item (index 0) in the array is the name of the Flash function to call, all the subsequent items are parameters to pass to the Flash object. To pass the correct arguments list to the Flash function, I want to pass only items with indexes 1..N.

An example of calling this is:

  calendarProxy.callFlashFunction( 'showWeek', 34, WeekDays.SUNDAY );

‘showWeek’ is the name of the Flash object function to call. 34 and WeekDays.SUNDAY are passed to showWeek as parameters.

So that is my use. If anybody has a suggestion on how I can improve this code, please let me know.

update April 27, 2010
Originally I used:

var args = [].splice.call( arguments, 0 );

But found that Internet Explorer would not support this.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Google Buzz Post to Reddit Post to Slashdot Post to StumbleUpon Post to Technorati

Comments are closed.