首页 > 其他 > 详细

2. es6扩展运算符

时间:2019-07-13 23:55:05      阅读:171      评论:0      收藏:0      [点我收藏+]

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

 

2. es6扩展运算符

原文:https://www.cnblogs.com/shiyun32/p/11182692.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!