es6之剩余和扩展参数

剩余参数(将多个东西合并成一个数组):

1.应用场景一:假设我们有这么一组数据,将第一个值赋值给班主任变量,第二个值赋值给班长变量,剩下的归为学生

这时我们就可以使用剩余参数...

    const team = ["班主任","班长","同学1","同学2","同学3"]
    const [boss,monitor,students] = team
    console.log(boss,monitor,students)  //班主任 班长 同学1
    const [boss,monitor,...students] = team
    console.log(boss,monitor,students)  //班主任 班长 (3) ["同学1", "同学2", "同学3"]

2.应用场景二:将传入的多个数字进行排序(因为传入的参数个数是不确定的,所以剩余参数就派上用场了)

    // ...nums不管你传入了多少个参数,都放到nums数组中
    function sortNums(...nums){
      if(nums.length === 0) {
        return []
      }else{
        //js的sort是有问题的,需要改造一下 正序排列a-b,倒序排列b-a
        return nums.sort((a,b) =>  a - b )
      }
    }
    console.log(sortNums(1,2,10))   //(3) [1, 2, 10]

扩展参数(将一个数组打散):

1.应用场景一:将班主任、班长、学生数组合并成一个数组

    const boss = "班主任"
    const monitor = "班长"
    const students = ["同学1","同学2","同学3"]
    const team = [boss,monitor,...students]
    console.log(team)    //["班主任", "班长", "同学1", "同学2", "同学3"]

2.应用场景二:将两个数组合并为一个数组

    const food = ["香辣鸡腿堡","墨西哥鸡肉卷","香辣烤翅"]
    const drink = ["百事可乐","橙汁"]
    // concat方法
    // const kfc = food.concat(drink)
    // console.log(kfc)  //(5) ["香辣鸡腿堡", "墨西哥鸡肉卷", "香辣烤翅", "百事可乐", "橙汁"]
    const kfc = [...food,...drink]
    console.log(kfc)  //(5) ["香辣鸡腿堡", "墨西哥鸡肉卷", "香辣烤翅", "百事可乐", "橙汁"]

还可以在新生成的数组中添加数据:

  const kfc = [...food,"圣代","吗媞娜",...drink]
    console.log(kfc)  //(5) ["香辣鸡腿堡", "墨西哥鸡肉卷", "香辣烤翅", "百事可乐", "橙汁"]

 

posted @ 2020-04-25 14:57  天空003  阅读(301)  评论(0编辑  收藏  举报