How to get a fragment from "arguments"

All you know is that arguments is a special object that contains all the arguments passed to the function.

And while this is not an array - you cannot use something like arguments.slice(1) .

So the question is how to cut everything except the first element from arguments ?

UPD

there seems to be no way without converting it to an array with

 var args = Array.prototype.slice.call(arguments); 

If someone publishes another solution, it would be great if it werenโ€™t - I would check the first one with the above line as an answer.

+67
javascript
Mar 01 2018-12-12T00:
source share
7 answers

Interaction with array functions is not really required.

Using the break parameter syntax ...rest is cleaner and more convenient.

Example

 function argumentTest(first, ...rest) { console.log("First arg:" + first); // loop through the rest of the parameters for(let arg of rest){ console.log("- " + arg); } } // call your function with any number of arguments argumentTest("first arg", "#2", "more arguments", "this is not an argument but a contradiction"); 

... Rest

+4
Nov 24 '17 at 9:41
source share

Q. How to cut everything except the first element from arguments ?

Next, an array containing all the arguments except the first one will be returned:

 var slicedArgs = Array.prototype.slice.call(arguments, 1); 

You do not need to convert arguments to an array first, do it all in one step.

+119
Mar 01 '12 at 3:26
source share

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments :

You should not slice the arguments, because this prevents optimization in JavaScript engines (e.g. V8). Instead, try building a new array, iterating through the arguments object.

So, Paul Rosiana's answer above is correct.

+11
Apr 30 '15 at 18:30
source share

You can "cut without slicing" by procedurally moving the arguments object:

 function fun() { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } return args; } fun(1, 2, 3, 4, 5); //=> [2, 3, 4, 5] 
+10
Mar 01 2018-12-12T00:
source share

It could be a way:

 var args = Array.from(arguments).slice(1); 
+3
Aug 21 '17 at 23:45
source share

You can use the [].slice.call(arguments, 1) method

[]. slice will return you a slice function object, and you can name it as arguments and 1 parameters

0
Dec 01 '17 at 15:50
source share

You can use ... rest inside the function to separate the first and other arguments:

 function foo(arr) { const [first, ...rest] = arguments; console.log('first = ${first}'); console.log('rest = ${rest}'); } //Then calling the function with 3 arguments: foo(1,2,3) 
0
Sep 04 '18 at 20:46
source share



All Articles