What is the meaning of “foo(…arg)” (three dots in a function call)?

后端 未结 4 2035
南旧
南旧 2021-01-12 07:30

Can someone tell what is \"...\" in the below code in the \"Intro to Angular\" example?

getHeroes() {
    this.backend.getAll(Hero).then( (heroes: Hero[]) =&         


        
4条回答
  •  离开以前
    2021-01-12 07:41

    As per the title of the question, the use of ... in a function declaration (within parenthesis) is that of a rest operator or rest parameter,In order to help us create more flexible functions, ES6 introduces the rest parameter for function parameters.

    With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.

    Example: 1

    function foo(...args) {
      return "You have passed " + args.length + " arguments.";
    }
    
    console.log(foo(0, 1, 2,4)); // You have passed 4 arguments.
    console.log(foo("hello", null, [1, 2], { })); // You have passed 4 arguments.
    

    Example 2:

    function foo(...args){
         args.forEach(function(arg){
            console.log(arg);
         })
       }
    
       foo(2,3,4,5,6);
    

    The rest parameter eliminates the need to check the args array and allows us to apply map(), filter(), reduce() and other array Higher Order functions on the parameters array.

    OTHER USE CASES OF ... operator :

    1. Used as spread operator which is the reverse of rest operator.

      const arr = [6, 89, 3, 45]; const maximum= Math.max(...arr); console.log(maximum);

    2. ... operator is used to copy the array or an object pretty easily and is quite helpful in javascript frameworks and libraries like angular and react respectively.

      const arr1 = [1,2,3,4];
      const arr2 = [...arr1];
      console.log(arr2);//  [1,2,3,4];
      
      const obj1 = {
        name:'john',
        age:25
      }
      
      const obj2 = {...obj1};
      console.log(obj2); // Now obj2 is new object and is copy of obj1 (non-mutated 
      way)
      

提交回复
热议问题