javascriptarguments-object

Why can't I call an array method on a function's arguments?


I have a function that can accept any number of arguments...

const getSearchFields = () => {        
    const joined = arguments.join('/'); 
};

I want a string of all the arguments being passed to the function joined with the / character. I keep getting this error:

args.join is not a function

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


Solution

  • 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, "/");