美文网首页
ES6 函数默认参数、rest运算符(扩展运算符)剩余参数

ES6 函数默认参数、rest运算符(扩展运算符)剩余参数

作者: 祝名 | 来源:发表于2018-12-14 19:03 被阅读0次

    一.函数默认参数

    1.旧函数默认参数写法

    function show(a, b){
        a = a || 'haha';
        b = b || 'hehe';
        console.log(a, b);
    }
    show('heihei');
    -->输出heihei hehe
    

    2.新函数默认参数写法

    function show(a = 'haha', b = 'hehe'){
        console.log(a, b);
    }
    show('heihei');
    -->输出heihei hehe
    
    function show({x=0,y=0}){
        console.log(x, y); 
    }
    show({x:1, y:2});
    
    或参数默认控制
    function show({x=0,y=0}={}){
        console.log(x, y); 
    }
    show();
    

    二.函数参数默认已经定义了,不能再使用let,const声明

    function show(a = 18){
        let a = 101;
        console.log(a);
    }
    show();
    -->报错
    

    三.rest运算符(扩展运算符)

    1. 三个点...

    • (1)数组扩展运算符,展开数组
    let arr = ['apple','banana','orange'];
    console.log(arr);
    -->输出['apple','banana','orange']
    console.log(...arr);
    -->输出 apple banana orange
    
    function show(a,b,c){
        console.log(a,b,c);
    }
    show(...[1,2,3]);
    
    • (2)收回数组
    function show(...a){
        console.log(a);
    }
    show(1,2,3,4,5);
    -->输出[1,2,3,4,5]
    
    • (3)也叫剩余运算符,rest运算符
      当做剩余运算符来用时,必须放在参数最后一位,不可以放在中间某个参数位置。
    function show(a,b,...c){
        console.log(a,b);
        console.log(c);
    }
    show(1,2,3,4,5);
    -->输出 1 2 [3,4,5]
    
    • (4)rest参数会获得函数调用的时候多余的参数

    2.配合函数排序使用

    function show(){
        let a = Array.prototype.slice.call(arguments);
        return a.sort();
    }
    console.log(show(1,9,8,2,3));
    

    等同于

    function show(...a){
        return a.sort();
    }
    console.log(show(1,9,8,2,3));
    

    3.复制数组

    let arr = [1,2,3,4];
    复制arr数组,有以下几种方法
    let arr1 = [...arr];
    let arr1 = Array.from(arr);
    

    相关文章

      网友评论

          本文标题:ES6 函数默认参数、rest运算符(扩展运算符)剩余参数

          本文链接:https://www.haomeiwen.com/subject/hmzwhqtx.html