ES6中的rest剩余参数和spread扩展运算符

一、剩余参数 rest
1、剩余参数语法允许我们将一个不定数量的参数表示为一个数组。

function sum (first, ...args) {
 console.log(first); // 10
 console.log(args); // [20, 30]
}
sum(10, 20, 30)

2、剩余参数和解构配合使用

let students = ['wangwu', 'zhangsan', 'lisi'];
let [s1, ...s2] = students;
console.log(s1); // 'wangwu'
console.log(s2); // ['zhangsan', 'lisi']

二、扩展运算符 spread
1、扩展运算符可以将数组或者对象转为用逗号分隔的参数序列。

let ary = [1, 2, 3];
...ary // 1, 2, 3
console.log(...ary); // 1 2 3
console.log(1, 2, 3)

2、扩展运算符可以应用于合并数组。

// 方法一
let ary1 = [1, 2, 3];
let ary2 = [3, 4, 5];
let ary3 = [...ary1, ...ary2];
// 方法二
ary1.push(...ary2);

3、将伪数组或可遍历对象转换为真正的数组

let oDivs = document.getElementsByTagName('div');
oDivs = [...oDivs];

在 ES9 新增 Object 的 Rest & Spread 方法

...rest的使用: rest 参数,用于获取函数的实参,用来代替 arguments

     const connect=({host,port,...user})=>{
        console.log(host)
        console.log(port)
        console.log(user)
     }
   //调用方法
     connect({
       host: '127.0.0.1',
       port: 3306,
       username: 'root',
       password: '123456',})

  //输出
 127.0.0.1
 38 3306
 {username: 'root', password: '123456'}

spread 语法,可以把一个对象的数据都拓展到另一个对象

    const a={a:'苹果'}
    const b={b:'香蕉'}
    const fruits={...a,...b}
    //const x={a:'xx',...b}
    console.log(fruits) // {a: '苹果', b: '香蕉'}
posted @ 2021-05-26 14:30  清和时光  阅读(440)  评论(0编辑  收藏  举报