展开运算符

普通写法与展开运算符

  • 普通数组相加
      function addNumbers(numbers) {
         return numbers.reduce((sum,number)=>{
             return sum+number
         },0)
       };
      
      const  numbers=[1,2,3,4,5];
      console.log(addNumbers(numbers))  //15
  • 如果传入的是单个数字

    function addNumbers(a,b,c,d,e) {
        let numbers=[a,b,c,d,e];
        return numbers.reduce((sum,number)=>{
            return sum+number
        },0)
    };

    console.log(addNumbers(1,2,3,4,5)) //15

  • 展开运算符

    function addNumbers(...numbers) {

        return numbers.reduce((sum,number)=>{
            return sum+number
        },0)
    };

    console.log(addNumbers(1,2,3,4,5)) //15

展开运算符的应用

  • 可替代数组push等操作

    var defaultColor=['red','green'];
    var favoriteColor=['orange','yellow'];

    defaultColor=defaultColor.concat(favoriteColor);

    console.log(defaultColor); //["red", "green", "orange", "yellow"]

    //同理也可以直接传两个数组
    console.log([...defaultColor,...favoriteColor])

    //之前的数组也可以合并

     var fallcolors=['fire red','fall orange'];
     
    console.log(['blue',...fallcolors,...defaultColor,...favoriteColor])

小案例

  • 判断某个值是否在某个数组中,如果没有,就添加进去

     function shopList(...items) {
         if(items.indexOf('milk')<0){
             return ['milk',...items]
         }
      };
    
      console.log(shopList('orange','bread','eggs'))