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

前端 未结 8 1277
鱼传尺愫
鱼传尺愫 2020-12-03 05:07

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

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


        
8条回答
  •  有刺的猬
    2020-12-03 05:30

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

    Edit: Since the original question asked almost 9 years ago was updated to use ES6 syntax, I feel the need to provide an ES6 answer now the language provides native constructs to handle this kind of situations.

    The ES6 standard introduces the spread operator, which you can easily use to receive the arguments as an array object, for example:

    function sum(...numbers) {
      return numbers.reduce((sum, value) => sum + value);
    }
    
    console.log(sum(1,2,3,4)); // 10

    Applied to your example:

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

    You can also use the spread operator to do function calls, let's say you have an array, and you want to call a function, passing each element of the array as an argument of the function call, now you can simply:

    function sum(a, b, c, d) {
      return a + b + c + d;
    }
    
    var array = [1, 2, 3, 4];
    console.log(sum(...array)); // 10

    Also you can expect some arguments and have the rest of the arguments passed as the last parameter defined:

    function processList(first, ...rest) {
      // ...
    }
    

    And there are more uses of the spread operator that go beyond the scope of this question, for example object copying, spreading arrays in arrays, etc...

提交回复
热议问题