zoukankan      html  css  js  c++  java
  • 扩展运算符(...)的用途

    1.合并数组
    一直以来,有很多方法合并数组,但是扩展运算符给了我们全新的方法去实现合并数组:

    arr1.push(...arr2) // 把arr2合并到arr1的后面
    arr1.unshift(...arr2) //把arr2合并到arr1的前面
    如果你想在数组内合并数组,你可以像下面这样做:

    var arr1 = ['two', 'three'];
    var arr2 = ['one', ...arr1, 'four', 'five'];
    2.复制数组
    复制数组是我们常常要做的工作,在过去,我们会使用Array.prototype.slice去实现,但现在我们可以使用扩展运算符去得到一个复制后的数组:

    var arr = [1,2,3];
    var arr2 = [...arr]; // 就像 arr.slice()
    arr2.push(4)
    3.结构赋值
    结构赋值是一个十分有趣的实践,我在自己的React项目中大量的使用了这种技巧。你可以使用扩展运算符配合其他运算符一起,从变量中提取有用的信息,就像这样:

    let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
    console.log(x); // 1
    console.log(y); // 2
    console.log(z); // { a: 3, b: 4 }


    ---------------------
    作者:yi_xiuge
    来源:CSDN
    原文:https://blog.csdn.net/yi_xiuge/article/details/76576211
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    luogu P3375 【模板】KMP字符串匹配
    leetcode[129]Sum Root to Leaf Numbers
    leetcode[130]Surrounded Regions
    leetcode[131]Palindrome Partitioning
    leetcode[132]Palindrome Partitioning II
    leetcode[133]Clone Graph
    leetcode[134]Gas Station
    leetcode[135]Candy
    leetcode[136]Single Number
    leetcode[137]Single Number II
  • 原文地址:https://www.cnblogs.com/aslxwjh/p/10319797.html
Copyright © 2011-2022 走看看