zoukankan      html  css  js  c++  java
  • 5 分钟掌握 JS 实用窍门技巧,帮你快速撸码--- 删除数组尾部元素、E6对象解构、async/await、 操作平铺嵌套多维数组等

    1. 删除数组尾部元素

    一个简单方法就是改变数组的length值:

    const arr = [11, 22, 33, 44, 55, 66]; 
    arr.length = 3;
    console.log(arr); //=> [11, 22, 33]
    arr.length = 0;
    console.log(arr); //=> []

    2. 使用对象解构

    let data = {
        message:"messages",
        title:"titles", 
    }
    
    let { message, title } = data;
    console.log(message, title);
    
    let { message:messages, title:titles } = data;
    console.log(messages, titles);

    3. 在 Switch 语句中使用范围值

    function getWaterState(tempInCelsius) {
      let state;
      switch (true) {
        case tempInCelsius <= 0:
          state = "Solid";
          break;
        case tempInCelsius > 0 && tempInCelsius < 100:
          state = "Liquid";
          break;
        default:
          state = "Gas";
      }
      return state;
    }

    4. await 多个 async 函数

    在使用 async/await 的时候,可以使用 Promise.all 来 await 多个 async 函数 

    await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])

    5. 从数组中移除重复元素

    通过使用集合语法和 Spread 操作,可以很容易将重复的元素移除:

    const removeDuplicateItems = arr => [...new Set(arr)];
    removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
    //=> [42, "foo", true]

    6. 平铺多维数组

    使用 Spread 操作平铺嵌套多维数组:

    const arr = [11, [22, 33], [44, 55], 66];
    const flatArr = [].concat(...arr);
    //=> [11, 22, 33, 44, 55, 66]

    希望这些小技巧能帮助你写好 JS ~

    有不对的地方还望大神指点一二

     
  • 相关阅读:
    [LeetCode] Same Tree, Solution
    图搜索
    1 sec on Large Judge (java): https://github.com/l...
    [LeetCode] Path Sum, Solution
    嗯哪
    海量数据处理总结
    [LeetCode] Unique Binary Search Trees II, Solution
    [Interview] Serialize and Deserialize a tree
    设计题
    [LeetCode] Convert Sorted Array to Binary Search Tree, Solution
  • 原文地址:https://www.cnblogs.com/BeautifulBoy/p/9783076.html
Copyright © 2011-2022 走看看