拓展运算符和剩余运算符

112 阅读1分钟

定义

扩展运算符:
    功能是把数组或对象展开成一系列用逗号隔开的值
剩余运算符:
    功能是把逗号隔开的值序列组合成一个数组

拓展运算符

合并数组或对象
    例1:
     const halfMonths1 = [1, 2, 3, 4, 5, 6];
     const halfMonths2 = [7, 8, 9, 10, 11, 12];

     const allMonths = [...halfMonths1, ...halfMonths2];
     console.log(allMonths); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
     
    例2:若有重复属性,会产生覆盖
     const pepole1 = {
        name: "zhangsan",
        age: 18,
      };
     const pepole2 = {
        age: 20,
        sex: 1,
      };
     console.log({...pepole1,pepole2});//{name:"zhangsan",age:20,sex:1}
     
进行浅拷贝(第一层)
    例1:
     const pepole = {
         name:"zhangsan",
         age:18,
         family:{
             son:1,
         }
      } 
      
      const pepole1 = {...pepole};
      pepole1.family.son = 2;
      pepole1.age = 19;
      console.log(pepole);
      //{
      //    name:"zhangsan",
      //      age:18,
      //      family:{
      //        son:2,
      //      }
      //}
      console.log(pepole1);
      //{
      //    name:"zhangsan",
      //      age:19,
      //      family:{
      //        son:2,
      //      }
      //}
      
打散传参
    例1:
     const sum = (num1, num2) => num1 - num2;
     console.log(...sum[7,6]);//1
     
    例2:
     const sum = (num1,num2) => num1 - num2;
     console.log(...sum[7,6,5]);//1
     
数组去重
    例1:
      const arr = [1,2,3,4,5,6,1,2,3];
      const arr1 = [new Set(...arr)];
      console.log(arr1);//[1,2,3,4,5,6]
      
打散字符串
    例1:
      const str = "name";
      consol.log([...str]);//['n','a','m','e']
      

剩余运算符

不确定输入参数个数
    例1:
     function pipe(...func) {
       console.log(func); //[1,2,3]
     }
     const compute = pipe(1, 2, 3);
       
    例2:
     function pipe(item,...arr){
        console.log(item);//1
        consoel.log(arr);//[2,3,4,5]
     }
     pipe(1,2,3,4,5);
     
参考文章
 https://www.jianshu.com/p/3928e0571874
 https://juejin.cn/post/6979840705921286180#heading-6