Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 358
alex Avatar asked Sep 15 '09 01:09

alex


People also ask

How do you pass an array as a function argument in JavaScript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.

Why are arrays not passed by value?

The reason you can't pass an array by value is because there is no specific way to track an array's size such that the function invocation logic would know how much memory to allocate and what to copy. You can pass a class instance because classes have constructors. Arrays do not.

Which one option will convert the arguments to an array?

Object. values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map , forEach , filter , etc.


1 Answers

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, "/"); 
like image 118
David Andres Avatar answered Sep 21 '22 13:09

David Andres