zoukankan      html  css  js  c++  java
  • 2. es6扩展运算符

    1. es扩展运算符

    扩展运算符将一个数组转为用逗号分隔的参数序列;

    <script>
        console.log(...[1, 2, 3]) //1 2 3
    
        // (1)将一个数组,变为参数序列
        let add = (x, y) => x + y;
        let numbers = [1, 2];
        console.log(add(...numbers))//3
    
        // (2)使用扩展运算符展开数组代替apply方法,将数组转为函数的参数
        // ES5 取数组最大值
        console.log(Math.max.apply(this, [654, 233, 727])); //727
        // ES6 扩展运算符
        console.log(Math.max(...[654, 233, 727])) //727
        // 相当于
        console.log(Math.max(654, 233, 727))//727
    
        // (3)使用push将一个数组添加到另一个数组的尾部
        // ES5  写法
        let arr1 = [1, 2, 3];
        let arr2 = [4, 5, 6];
        Array.prototype.push.apply(arr1, arr2);
        console.log(arr1) // [1, 2, 3, 4, 5, 6]
        // push方法的参数不能是数组,通过apply方法使用push方法
        // ES6  写法
        let arr3 = [1, 2, 3];
        let arr4 = [4, 5, 6];
        arr3.push(...arr4);
        console.log(arr3) // [1, 2, 3, 4, 5, 6]
    
        // (4)合并数组
        let a = ['a', 'b'];
        let b = ['c'];
        let c = ['d', 'e'];
        // ES5 的合并数组
        let d = a.concat(b, c);
        console.log(d) //["a", "b", "c", "d", "e"]
        // ES6 的合并数组
        let e = [...a, ...b, ...c]
        console.log(e) //["a", "b", "c", "d", "e"]
    
        // (6)将字符串转换为数组
        let h = [...'hello']
        console.log(h) //["h", "e", "l", "l", "o"]
        // ES5
        let str = 'world'.split('') //["w", "o", "r", "l", "d"]
        console.log(str)
    
        // (6)转换伪数组为真数组
        var nodeList = document.querySelectorAll('p');
        console.log(nodeList)
        var array = [...nodeList];
        console.log(array)
        // 具有iterator接口的伪数组,非iterator对象用Array.from方法
    
        // (7)map结构
        let map = new Map([
            [1, 'one'],
            [2, 'two'],
            [3, 'three'],
        ]);
        let arr = [...map.keys()];
        console.log(arr) //[1, 2, 3]
    
    </script>

    参考文档:

      es6三点扩展运算符

  • 相关阅读:
    在页面生命周期执行时 Page 对象在 SaveState 阶段都发生了什么事?
    接收Firfox RESTClient #Post请求
    c# 单例模式[Singleton]之深夜闲聊
    JQuery 之 Ajax 异步和同步浅谈
    [模板]数学整合
    Yandex插件使用说明——Slager_Z
    模板练习(LUOGU)
    数学整合 新(LUOGU)
    [NOI.AC]DELETE(LIS)
    [NOI.AC]COUNT(数学)
  • 原文地址:https://www.cnblogs.com/shiyun32/p/11182692.html
Copyright © 2011-2022 走看看