• 一些便捷的ES语法使用记录


    Object.values()

    const exampleObj = {a: 1, b: 2, c: 3, d:4};
    console.log(Object.value(exampleObj)); // [1, 2, 3, 4];
    
    • 1
    • 2

    Object.keys()

    const values = Object.keys(exampleObj).map(key => exampleObj[key]);
    
    • 1

    Object.entries()

    const exampleObj = {a: 1, b: 2, c: 3, d:4};
    console.log(Object.entries(exampleObj)); // [["a", 1], ["b", 2], ["c", 3], ["d", 4]];
    
    for (const [key, value] of Object.entries(exampleObj)) {
      console.log(`key: ${key}, value: ${value}`);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    字符串 padStart()

    String.padStart(fillingLength, FillingContent);
    '100'.padStart(5, '987'); // 98100
    
    • 1
    • 2

    字符串 padEnd()

    '100'.padStart(5, '987'); // 10098
    
    • 1

    ES9 异步迭代器

    允许 await 与 for 循环一起使用,逐步执行异步操作

    async function process(array) {
      for await (const i of array) {
        doSomething(i);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Math.max()

    const values = [19, 90, -2, 6, 25];
    console.log( Math.max(...values) ); // 90
    
    • 1
    • 2

    正则表达式组

    RegExp 可以返回匹配的数据包

    const regExpDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/;
    const match      = regExpDate.exec('2020-06-25');
    const year       = match[1]; // 2020
    const month      = match[2]; // 06
    const day        = match[3]; // 25
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Array.prototype.flat()

    展平阵列

    const arr1 = [1, 2, [3, 4]];
    arr1.flat(); // [1, 2, 3, 4]
    const arr2 = [1, 2, [3, 4, [5, 6]]];
    arr2.flat(); // [1, 2, 3, 4, [5, 6]]
    arr2.flat(2); // [1, 2, 3, 4, 5, 6]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Array.prototype.flatMap()

    展平一个维度

    let arr = ["早安", "", "今天天氣不錯"]
    arr.map(s => s.split(""))
    // [["早", "安"], [""], ["今", "天", "天", "氣", "不", "錯"]]
    arr.flatMap(s => s.split(''));
    // ["早", "安", "", "今", "天", "天", "氣", "不", "錯"]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    String.prototype.trimStart()

    开头删除空格,别名trimLeft()

    const greeting = ‘ Hello world!;
    console.log(greeting.trimStart());
    // expected output: “Hello world! “;
    
    • 1
    • 2
    • 3

    String.prototype.trimEnd()

    末尾删除空格,别名trimRight()

    const greeting = '   Hello world!   ';
    console.log(greeting.trimEnd());
    // expected output: "   Hello world!";
    
    • 1
    • 2
    • 3

    Object.fromEntries()

    将键值对列表转换为对象

    const entries = new Map([
      ['foo', 'bar'],
      ['baz', 42]
    ]);
    const obj = Object.fromEntries(entries);
    console.log(obj);
    // expected output: Object { foo: "bar", baz: 42 }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Promise.allSettled()

    返回一个在所有给定的 Promise 都已实现或拒绝后实现的 Promise,并带有一组对象,每个对象都描述了每个 Promise 的结果

    const promise1 = Promise.resolve(3);
    const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
    const promises = [promise1, promise2];
    Promise.allSettled(promises).
      then((results) => results.forEach((result) => console.log(result.status)));
    // expected output:
    // "fulfilled"
    // "rejected"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    可选链接?

    //如果存在,获取name的值,如果不存在,赋值undefined
    const username = user?.name || 'guest';
    
    • 1
    • 2

    Nullish 合并运算符 ??

    在JavaScript中,遇到0、null、undefuded时会自动转为false,但有时0其实是一个正常的值,只能容错undefined和null

    const username = user.level ?? 'no level'; 
    // output 0. if level is not available, it becomes 'no level'.
    
    • 1
    • 2

    Dynamic-import

    在需要的时候加载相关的逻辑

    el.onclick = () => {
        import(`/js/current-logic.js`)
        .then((module) => {
            module.doSomthing();
        })
        .catch((err) => {
            handleError(err);
        })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    ||= , &&= , ??=

    ES2021 会提出 ||= , &&= , ??= ,概念类似于 += :

    let b = 2
    b += 1 
    // equal to b = b + 1
    let a = null
    a ||= 'some random text'  // a become to'some random text'
    // equal a = a || 'some random text'
    let c = 'some random texts'
    c &&= null  // c become to null
    // equal to c = c && null
    let d = null
    d ??= false  // d become to false
    // equal to d = d ?? false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    「PAT乙级真题解析」Basic Level 1003 我要通过! (问题分析+完整步骤+伪代码描述+提交通过代码)
    Python基础入门例程18-NP18 生成数字列表(列表)
    猿创征文|我的前端成长之路
    访问修饰符你用对了吗
    网络-TCP关闭连接(close、shutdown)
    猿创征文|2022个人开发工具集积累和分享
    【JAVA】Scanner的next()、nextInt()、nextLine()读取机制
    Makefile教程
    第三章 内存管理 七、具有快表的地址变换结构
    log4j 基础使用入门教程
  • 原文地址:https://blog.csdn.net/weixin_43996368/article/details/127622103