ES6参数默认值与rest参数

参数默认值:

ES6新增默认参数功能,参数可以有默认值(初始值),通常有默认值的写在最后

	// 解构
    let obj = {
        host: "192.168.1.1",
        username: "王一",
        password: 123456,
    }
    function connect({ host, username, password, port = 3006 }) { //port=3006 设置参数默认值
        console.log(host);
        console.log(username);
        console.log(password);
        console.log(port);
    }
    connect(obj);

rest参数:

ES6无法获取arguments集合,rest参数来代替

	// ...拓展运算符 rest参数来代替
    function showName1(a, b, ...rest) { //把3,4,5 用[] 包住,变成数组
        // console.log(a);
        // console.log(b);
        console.log(rest);
    }
    showName1(1, 2, 3, 4, 5); //Array(3)[3, 4, 5]  

    // arguments
    function showName2(a, b, c) {
        // console.log(a);
        // console.log(b);
        console.log(arguments);
    }
    showName2(1, 2, 3, 4, 5); //Arguments(5)[1, 2, 3, 4, 5]

… 拓展运算符 rest反作用:可以将 数组展开成,分割的参数列表

 	let arr = [1, 2, 3];
    console.log(arr); //Array(3) [1, 2, 3]
    console.log(...arr); // 1 2 3
    //需要将数组转化为参数形式,传递到某个函数中
    let goods = [4, 5, 6];
    goods.push(...arr);
    console.log(goods); //Array(6)[4, 5, 6, 1, 2, 3]
    // 完美取代了apply
    let max = Math.max(...goods);
    console.log(max); //6

利用拓展运算符,结构数组 :

 	// 展开:
    let arr = [1, 2, 3];
    let goods = [...arr]; //拓展运算符展开 
    goods.push(4);
    console.log(arr); //[1, 2, 3]
    console.log(goods); //[1, 2, 3, 4]

    // 合并:
    let arr = [1, 2, 3];
    let goods = [4, 5, 6];
    let x = [...arr, ...goods]; //拓展运算符合并
    console.log(arr); //[1, 2, 3]
    console.log(goods); //[4, 5, 6]
    console.log(x); //[1, 2, 3,4,5,6]

利用拓展运算符,解构对象:

	let obj = {
        a: 1,
        b: 2,
        c: 3,
        d: 4
    }
    let { a, b, ...z } = obj;
    console.log(a); //1
    console.log(b); //2
    console.log(z); //{c: 3, d: 4}
    
    let n = {
        ...obj
    }
    console.log(n); //{a: 1, b: 2, c: 3, d: 4}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值