views:

324

answers:

4

I have a function that accepts multiple arguments (only one is defined in the function though)

var getSearchFields = function(method) {

    console.log(arguments); // this prints them out nicely into the console

    var args = arguments;

    var argsString = args.join('/'); // I expect 'arg1/arg2/arg3', instead I get 'args.join is not a function'
}

I just want a string of all the arguments being sent to the function. I keep getting this error:

args.join is not a function

Can someone please tell me what I'm doing wrong?

Thanks

+9  A: 

arguments is a pseudo-array, not a real one. The join method is available for arrays.

You'll need to cheat:

var convertedArray = [];

for(var i = 0; i < arguments.length; ++i)
{
 convertedArray.push(arguments[i]);
}

var argsString = convertedArray.join('/');

Similar to other posts, you can do the following as shorthand:

var argsString = Array.prototype.join.call(arguments, "/");
David Andres
To convert the arguments object to an array, you could simply: `var convertedArray = Array.prototype.slice.call(arguments);`
CMS
you could also simplify the loop by using splice.... var args = [].splice.call(arguments,0);
Russ Bradberry
@Russ: Shorter but will not work on IE, you should call directly the Array.prototype.slice function.
CMS
A: 

arguments is not a JavaScript array; it's a special object that doesn't have a join method.

Cory Larson
+2  A: 

arguments is not really an array.

try this:

var args = [].splice.call(arguments,0);
var argsString = args.join('/');
Russ Bradberry
+2  A: 

As all said above, the arguments object is not really an array, but you can apply array functions directly, by accessing the Array.prototype and executing them with apply or call to change the context:

var argsString = Array.prototype.join.call(arguments, '/');
CMS
'/' needs to be surrounded by brackets
David Andres
Nope, I'm using call, not apply
CMS
...correction, this might need to be the case when apply is called. You're using call. My mistake.
David Andres