What do these three dots in React do?

前端 未结 29 2589
不思量自难忘°
不思量自难忘° 2020-11-21 23:53

What does the ... do in this React (using JSX) code and what is it called?



        
29条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 00:22

    The three dots represent the Spread Operator in ES6. It allows us to do quite a few things in Javascript:

    1. Concatenate arrays

      var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil'];
      var racingGames = ['Need For Speed', 'Gran Turismo', 'Burnout'];
      var games = [...shooterGames, ...racingGames];
      
      console.log(games)  // ['Call of Duty', 'Far Cry', 'Resident Evil',  'Need For Speed', 'Gran Turismo', 'Burnout']
      
    2. Destructuring an array

        var shooterGames = ['Call of Duty', 'Far Cry', 'Resident Evil'];
        var [first, ...remaining] = shooterGames;
        console.log(first); //Call of Duty
        console.log(remaining); //['Far Cry', 'Resident Evil']
      
    3. Combining two objects

      var myCrush = {
        firstname: 'Selena',
        middlename: 'Marie'
      };
      
      var lastname = 'my last name';
      
      var myWife = {
        ...myCrush,
        lastname
      }
      
      console.log(myWife); // {firstname: 'Selena',
                           //   middlename: 'Marie',
                           //   lastname: 'my last name'}
      

    There's another use for the three dots which is known as Rest Parameters and it makes it possible to take all of the arguments to a function in as one array.

    1. Function arguments as array

       function fun1(...params) { 
      
       }  
      

提交回复
热议问题