How to get a slice from “arguments”

后端 未结 7 1897
天命终不由人
天命终不由人 2020-12-01 09:10

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

And as long as it is not an array - you cannot use

相关标签:
7条回答
  • 2020-12-01 09:11

    This can be a way:

    var args = Array.from(arguments).slice(1);
    
    0 讨论(0)
  • 2020-12-01 09:13

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

    [].slice will return you the slice function object and you can call it as the arguments and 1 are the parameters

    0 讨论(0)
  • 2020-12-01 09:14

    You can "slice without slicing" by procedurally walking 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]
    
    0 讨论(0)
  • 2020-12-01 09:17

    Q. How to slice everything but first element from arguments?

    The following will return an array containing all arguments except the first:

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

    You don't have to convert arguments to an array first, do it all in one step.

    0 讨论(0)
  • 2020-12-01 09:23

    You can use ...rest within the function to separate the first and the rest of the 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 讨论(0)
  • 2020-12-01 09:25

    Meddling with array functions is not actually necessary.

    Using rest 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

    • See the example Fiddle
    • See MDN Documentation page
    0 讨论(0)
提交回复
热议问题