美文网首页
ES6之扩展运算符与应用(数组篇)

ES6之扩展运算符与应用(数组篇)

作者: 雨飞飞雨 | 来源:发表于2017-09-25 12:02 被阅读627次

    1.含义

    扩展运算符(spread)就是我们知道的三个点(...),它就好像rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。

    console.log(...[1,2,3]);
    //1 2 3
    console.log(1,...[2,3,4],5)
    //1 2 3 4 5
    [...document.querySelectorAll('div')]
    // [<div>, <div>, <div>]
    

    扩展运算符主要用于函数调用。例如:

    function push(array,...items){
        array.push(...items);
    }
    
    function add(x,y){
        return x+y;
    }
    var numbers = [4,40]
    add(...numbers) //44
    
    
    function addNumbers(x,y,z){
        return x+y+z;
    }
    
    var numbers = [1,2,3,4];
    addNumbers(...numbers); //6
    

    上面代码中,array.push(...items)和add(...numbers)这两行,都是函数的调用,他们都使用了扩展运算符,该运算符将一个数组,变为参数序列。例如上面addNumbers,有三个参数,而数组则是4个元素,我们在计算的时候,只是取了前三个元素作为参数放到函数中进行运算,得到 6.

    扩展运算符与政策的函数参数可以结合使用,非常灵活。例如:

    function f(x,y,z,v,w){}
    var args = [0,1];
    f(-1,...args,2,...[3]);
    

    上面的例子中,...args是传入了两个参数,而...[3]则是传入了一个参数。

    扩展运算符后面还可以放置表达式。

    const arr = [
        ...(x > 0 ? ['a']:[]),'b'
    ];
    

    如果扩展运算符后面是一个空数组,则不产生任何的效果。

    [...[],1]
    //[1]
    

    2.可以替代数组的apply方法

    由于扩展运算符可以展开数组,所以不再需要apply方法,将数组转为函数的参数了。

    //ES5的写法
    function f(x,y,z){
        //...
    }
    
    var args = [0,1,2];
    f.apply(null,args);
    
    //ES6的写法
    function f(x,y,z){
        //...
    }
    
    var args = [0,1,2];
    f(...args);
    
    

    始终记得扩展运算符的含义就是,将数组转为函数的参数序列。
    下面是扩展运算符取代apply方法的一个实际例子,应用Math.max方法,简化求出一个数组最大元素的写法。

    //ES5 的写法
    Math.max.apply(null,[14,3,7])
    
    //ES6的写法
    Math.max(...[14,3,7]);
    
    //等同于
    Math.max(14,3,7);
    

    上面代码中,由于JavaScript不提供求数组最大元素的函数,所以只能套用Math.max函数。将数组转为一个参数序列。然后求最大值。有了扩展运算符,就可以直接用Math.max了。

    另一个例子是通过push函数,将一个数组添加到另一个数组的尾部。

    //ES5的写法
    var arr1 = [0,1,2];
    var arr2 = [3,4,5];
    Array>prototype.push.apply(arr1,arr2);
    
    //ES6的写法
    
    var arr1 = [0,1,2];
    var arr2 = [3,4,5];
    arr1.push(...arr2);
    

    上面代码的ES5写法中,push方法的参数不能是数组,所以只好通过apply方法变通使用push方法。有了扩展运算符,就可以直接将数组传入push方法。

    下面是另一个例子。

    // ES5
    new (Date.bind.apply(Date, [null, 2015, 1, 1]))
    // ES6
    new Date(...[2015, 1, 1]);
    

    3.扩展运算符的使用

    (1) 合并数组

    扩展运算符提供了数组合并的新写法。

    //ES5
    [1,2].concat(more);
    //ES6
    [1,2,...more]
    
    var arr1 = ['a', 'b'];
    var arr2 = ['c'];
    var arr3 = ['d', 'e'];
    
    //ES5的合并数组
    arr1.concat(arr2,arr3);
    // [ 'a', 'b', 'c', 'd', 'e' ]
    
    //ES6的合并数组
    [...arr1,...arr2,...arr3]
    // [ 'a', 'b', 'c', 'd', 'e' ]
    
    

    (2) 与解构赋值结合

    扩展运算符可以与结构赋值结合起来,用于生成数组。

    //ES5
    a = list[0],rest = list.slice(1);
    //ES6
    [a,...rest] = list;
    

    还有这样子:

    const [first,...rest] = [1,2,3,4,5];
    first //1
    rest //[2,3,4,5]
    
    const [first,...rest] = [];
    first //undefined
    rest //[]
    const [first,...rest] = ['foo'];
    first //'foo'
    rest //[]
    
    

    如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。

    const [...butlast,last] = [1,2,3,4,5,6];
    //报错
    const [first ,...middle,last] = [1,2,3,4,5];
    //报错
    const [first , middle,...last] = [1,2,3,4,5];
    
    console.log(last)
    //[3, 4, 5]
    

    (3) 函数的返回值

    JavaScript的函数只能返回一个值,如果需要返回多个值,只能返回数组或对象。扩展运算符提供了解决这个问题的一种变通个方法。

    var dateFieleds = readDataFields(database);
    var d = new Date(...dateFields);
    

    上面代码从数据库取出一行数据,通过扩展运算符,直接将其传入构造函数Date。

    (4) 字符串

    扩展运算符还可以将字符串转为真正的数组。

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

    上面的写法,有一种重要的好处,那就是能够正确识别32位的Unicode字符。

    'x\uD83D\uDE80y'.length // 4
    [...'x\uD83D\uDE80y'].length // 3
    

    上面代码的第一种写法,JavaScript会将32位Unicode字符,识别为2个字符,采用扩展运算符就没有这个问题。因此,正确返回字符串长度的函数,可以像下面这样写。

    function length(){
        return [...str].length;
    }
    length('x\uD83D\uDE80y') // 3
    

    凡是涉及到操作32位 Unicode 字符的函数,都有这个问题。因此,最好都用扩展运算符改写。

    let str = 'x\uD83D\uDE80y';
    
    str.split('').reverse().join('')
    // 'y\uDE80\uD83Dx'
    
    [...str].reverse().join('')
    // 'y\uD83D\uDE80x'
    

    上面代码中,如果不用扩展运算符,字符串的reverse操作就不正确。

    (5) 实现了Iterator接口的对象

    任何Iterator接口的对象(参阅Iterator文字),都可以用扩展运算符转为真正的数组。

    var nodeList = document.querySelectorAll('div');
    var array = [...nodeList];
    

    上面代码中,querySelectorAll方法返回的是一个nodeList对象。它不是数组,而是一个类似数组的对象。这时,扩展运算符可以将其转为真正的数组,原因在于NodeList对象实现了Iterator接口。

    对于那些没有部署Iterator接口的类似数组的对象,扩展运算符就无法将其转为真正的数组了。

    let arrayLike = {
      '0': 'a',
      '1': 'b',
      '2': 'c',
      length: 3
    };
    
    // TypeError: Cannot spread non-iterable object.
    let arr = [...arrayLike];
    

    上面代码中,arrayLike是一个类似数组的对象,但是没有部署 Iterator 接口,扩展运算符就会报错。这时,可以改为使用Array.from方法将arrayLike转为真正的数组。

    (6) Map 和 Set 结构,Generator函数

    扩展运算符内部调用的是数据结构的Iterator接口,因此只要具有Iterator接口的对象,都可以使用扩展运算符,比如Map结构,Set结构。

    let map = new Map([
        [1,'one'],
        [2,'two'],
        [3,'three'],
    ]);
    
    let arr = [...map.keys()] //[1,2,3]
    

    Generator函数运行后,返回一个遍历器对象,因此也可以使用扩展运算符。

    var go = function*(){
      yield 1;
      yield 2;
      yield 3;
    };
    
    [...go()] // [1, 2, 3]
    

    上面代码中,变量go是一个 Generator 函数,执行后返回的是一个遍历器对象,对这个遍历器对象执行扩展运算符,就会将内部遍历得到的值,转为一个数组。

    如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错。

    var obj = {a: 1, b: 2};
    let arr = [...obj]; // TypeError: Cannot spread non-iterable object
    

    扩展运算符与Set结构的结合使用

    扩展运算符(...)内部使用for...of循环,所以也可以用于 Set 结构。
    比如:Set结构转为数组

    let set = new Set(['red', 'green', 'blue']);
    let arr = [...set];
    // ['red', 'green', 'blue']
    

    扩展运算符和Set结构相结合,就可以去除数组的重复成员。因为Set结构没有重复的元素。

    let arr = [3, 5, 2, 2, 5, 5];
    let unique = [...new Set(arr)];
    // [3, 5, 2]
    

    通过扩展运算符,Set结构转为数组后就可以使用数组的map方法和filter方法:

    let set = new Set([1, 2, 3]);
    set = new Set([...set].map(x => x * 2));
    // 返回Set结构:{2, 4, 6}
    
    let set = new Set([1, 2, 3, 4, 5]);
    set = new Set([...set].filter(x => (x % 2) == 0));
    // 返回Set结构:{2, 4}
    

    扩展运算符和Set实现并集,交集,差集:

    let a = new Set([1,2,3]);
    let b = net Set([4,3,2]);
    
    //并集
    let union = new Set([...a,...b]);
    // Set {1, 2, 3, 4}
    //交集
    let intersect = new Set([...a].filter(x => b.has(x)));
    // set {2, 3}
    //差集
    let difference = new Set([...a].filter(x => !b.has(x)));
    // Set {1}
    

    扩展运算符与Map结构的结合使用

    使用扩展运算符(...),是最方便的Map转为数组的方法

    const myMap = new Map()
      .set(true, 7)
      .set({foo: 3}, ['abc']);
    [...myMap]
    // [ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ]
    

    Map各种遍历转为数组:

    const map = new Map([
      [1, 'one'],
      [2, 'two'],
      [3, 'three'],
    ]);
    
    [...map.keys()]
    // [1, 2, 3]
    
    [...map.values()]
    // ['one', 'two', 'three']
    
    [...map.entries()]
    // [[1,'one'], [2, 'two'], [3, 'three']]
    
    [...map]
    // [[1,'one'], [2, 'two'], [3, 'three']]
    

    通过扩展运算符,Map遍历转为数组就可以使用数组的map方法和filter方法了。

    const map0 = new Map()
      .set(1, 'a')
      .set(2, 'b')
      .set(3, 'c');
    
    const map1 = new Map(
      [...map0].filter(([k, v]) => k < 3)
    );
    // 产生 Map 结构 {1 => 'a', 2 => 'b'}
    
    const map2 = new Map(
      [...map0].map(([k, v]) => [k * 2, '_' + v])
        );
    // 产生 Map 结构 {2 => '_a', 4 => '_b', 6 => '_c'}
    

    WeakMap和WeakSet 与扩展运算符

    WeakMap和WeakSet由于不能遍历,也就是没有实现Iterator接口,所以不能使用扩展运算符。
    使用会报错,例如:

    const weakMap = new WeakMap();
    const arr = [...weakMap];
    VM187089:1 Uncaught TypeError: weakMap[Symbol.iterator] is not a function
        at <anonymous>:1:17
        
        
    const weakSet = new WeakSet();
    const arrs = [...weakSet];
    VM187363:1 Uncaught TypeError: weakSet[Symbol.iterator] is not a function
        at <anonymous>:1:18    
    

    学习文章:ES6之数组的扩展第一章

    相关文章

      网友评论

          本文标题:ES6之扩展运算符与应用(数组篇)

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