ES6扩展——函数扩展之剩余函数

1、结合扩展运算符

            //剩余参数是做聚合的,扩展运算符是做展开的
            function sum(...args){
                console.log(arguments);
                console.log(arguments instanceof Array);  //false 因为它是一个类数组对象
                
                //以下代码均可将类数组转成数组
                //let args = Array.prototype.slice.call(arguments);
                //let args = [...arguments];
                //let [...args] = arguments;
                //或者在函数参数的前面加三个点,即剩余参数
                
                console.log(args);  // [1,2,321,4354,'fdafsd']
            }
            sum(1,2,321,4354,'fdafsd');
            
            

 

2、有多个参数时

            //有多个参数时
            function op(type, ...nums){
                console.log(type);  //sum
                console.log(nums);  //[1, 23, 454, 3, 67, 234]
            }
            op('sum', 1, 23, 454, 3, 67, 234);
            

 

3、剩余参数必须是参数中的最后一位,否则报错

            //需要注意的是,剩余参数必须是最后一位,否则会报错,例如:
            function op(type, b, ...nums, d){
                console.log(type);
                console.log(nums); //Rest parameter must be last formal parameter
            }
            op('sum', 1, 23, 454, 3, 67, 234);
            
            

 

4、剩余参数和reduce函数结合

            //用剩余参数和reduce函数结合,使参数相加
            function sum1(...numbers){
                return numbers.reduce(function(a,b){
                    return a + b;
                },0);
            }
            console.log(sum1(1,2,3,4))  //10
            

 

4.1

reduce函数的第一个参数是回调函数,第二个参数是表示第一次遍历的值为多少。回调函数中的两个参数,a表示上一次return的值,b表示这次遍历到的一个项,
 
arr.reduce(function(prev,cur,index,arr){
...
}, init);
arr 表示原数组;
prev 表示上一次调用回调时的返回值,或者初始值 init;
cur 表示当前正在处理的数组元素;
index 表示当前正在处理的数组元素的索引,若提供 init 值,则索引为0,否则索引为1;
init 表示初始值。
常用的参数只有两个:prev 和 cur。
原理:由于传入了初始值0,所以开始时a的值为0,b的值为数组第一项1,相加之后返回值为1作为下一轮回调的a值,然后再继续与下一个数组项相加,以此类推,直至完成所有数组项的和并返回。
第一轮 a=0(init默认值0),b=1; 返回值:a=1;
第二轮:a=1,b=2, ;返回值:a=3;
第三轮:a=3 ,b=3;返回值:a=6;
第四轮:a=6,b=4-----返回值:a=10

 

posted @ 2020-06-17 01:34  是桂  阅读(224)  评论(0编辑  收藏  举报