ES7的... 用法

一、将一个数组转为用逗号分隔的参数序列。(若数组为空不产生任何效果)
    console.log(1, ...[2, 3, 4], 5)     // 1 2 3 4 5
    [...document.querySelectorAll('div')]     // [<div>, <div>, <div>]

二、复制数组(a2复制a1,这种方法之后再改变a2也不会影响到a1)
    const a1 = [1, 2];
        // 写法一
    const a2 = [...a1];
        // 写法二

    const [...a2] = a1;

三、合并数组(不过,这两种方法都是浅拷贝)
    const arr1 = ['a', 'b'];
    const arr2 = ['c'];
    const arr3 = ['d', 'e'];
        // ES5 的合并数组
    arr1.concat(arr2, arr3);  // [ 'a', 'b', 'c', 'd', 'e' ]
        // ES6 的合并数组

    [...arr1, ...arr2, ...arr3]    // [ 'a', 'b', 'c', 'd', 'e' ]

四、与解构赋值结合(注意:扩展符项必须放在最后一位)
    ① const [first, ...rest] = [1, 2, 3, 4, 5];
        first // 1
        rest  // [2, 3, 4, 5]
    ② const [first, ...rest] = [];
        first // undefined

        rest  // []

五、可以将字符串转为真正的数组

        [...'hello']     // [ "h", "e", "l", "l", "o" ]

六、Map 和 Set 结构,Generator 函数
    ①扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如     Map结构。
    let map = new Map([[1, 'one'],[2, 'two'],[3, 'three']]);
    let arr = [...map.keys()];     // [1, 2, 3]
    ②Generator 函数
    const go = function*(){
          yield 1;
          yield 2;
          yield 3;
     };
[...go()] // [1, 2, 3]
--------------------- 
作者:hyupeng1006 
来源:CSDN 
原文:https://blog.csdn.net/hyupeng1006/article/details/80769185 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_37806077/article/details/84562232
ES7