微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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三点扩展运算符

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐