关于JavaScript中ES6之后的一些版本改动

290 阅读4分钟

ECMAScript 2015(ES6)之后,JavaScript(ECMAScript)版本发布了多个重要的更新。每个新版本都带来了新的功能、改进和修复。下面是ES6之后的主要版本及其一些重要变更:

1. ECMAScript 2016 (ES7)

发布于 2016 年 6 月。

主要变更:

  • Array.prototype.includes():新增 Array.prototype.includes() 方法,用于判断数组是否包含某个元素,代替了 indexOf()

    [1, 2, 3].includes(2); // true
    [1, 2, 3].includes(4); // false
    
  • 指数操作符(Exponentiation Operator):新增 ** 操作符,作为替代 Math.pow() 的简写。

    console.log(2 ** 3); // 8
    

2. ECMAScript 2017 (ES8)

发布于 2017 年 6 月。

主要变更:

  • asyncawait:引入了 async 函数和 await 关键字,用于简化异步代码的写法,避免回调地狱。

    async function fetchData() {
        let response = await fetch('https://api.example.com');
        let data = await response.json();
        console.log(data);
    }
    fetchData();
    
  • Object.entries()Object.values()

    • Object.entries():返回一个对象的键值对数组。
    • Object.values():返回对象的所有值组成的数组。
    const obj = { a: 1, b: 2 };
    console.log(Object.entries(obj)); // [['a', 1], ['b', 2]]
    console.log(Object.values(obj)); // [1, 2]
    
  • String.prototype.padStart()String.prototype.padEnd():用于给字符串补充指定字符,使其达到指定长度。

    '5'.padStart(2, '0'); // '05'
    '5'.padEnd(3, '0');   // '500'
    
  • SharedArrayBuffer 和 Atomics:为多线程开发提供了支持,用于在 Web Workers 中进行共享内存操作。

3. ECMAScript 2018 (ES9)

发布于 2018 年 6 月。

主要变更:

  • 异步迭代(async iterators):新增 for-await-of 循环,允许在异步迭代器上进行迭代。

    async function fetchData() {
        const asyncIterable = getAsyncIterable(); // 假设返回一个异步可迭代对象
        for await (const item of asyncIterable) {
            console.log(item);
        }
    }
    
  • Rest/Spread 属性:允许对象解构时使用剩余参数(...)或展开运算符(...)来收集或展开对象属性。

    const obj = { a: 1, b: 2, c: 3 };
    const { a, ...rest } = obj; // { b: 2, c: 3 }
    
  • RegExp 的改进

    • RegExp.prototype.flags:新增 flags 属性,返回正则表达式的标志。
    • RegExpdotAll标志:允许点号(.)匹配所有字符,包括换行符。
    const regex = /./s;
    console.log(regex.test('\n')); // true
    

4. ECMAScript 2019 (ES10)

发布于 2019 年 6 月。

主要变更:

  • Array.prototype.flat()Array.prototype.flatMap()

    • flat():将多维数组扁平化为一维数组。
    • flatMap():首先使用映射函数映射每个元素,然后将结果扁平化。
    [1, [2, [3, 4]]].flat(2); // [1, 2, 3, 4]
    [1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
    
  • Object.fromEntries():与 Object.entries() 相反,允许将一个键值对的数组转换成一个对象。

    const entries = [['a', 1], ['b', 2]];
    const obj = Object.fromEntries(entries);
    console.log(obj); // { a: 1, b: 2 }
    
  • String.prototype.trimStart()String.prototype.trimEnd():用于修剪字符串的开始或结尾的空格。

    '  hello '.trimStart(); // 'hello '
    '  hello '.trimEnd();   // '  hello'
    
  • Symbol.prototype.description:可以直接访问 Symbol 的描述。

    const sym = Symbol('description');
    console.log(sym.description); // 'description'
    

5. ECMAScript 2020 (ES11)

发布于 2020 年 6 月。

主要变更:

  • BigInt:新增 BigInt 类型,支持任意精度的大整数。

    const bigInt = 123456789012345678901234567890n;
    console.log(bigInt + 1n); // 123456789012345678901234567891n
    
  • Promise.allSettled():返回一个 Promise,解决为所有给定 Promise 的结果,包含成功和失败的结果。

    const promises = [Promise.resolve(1), Promise.reject('error')];
    Promise.allSettled(promises).then(results => {
      console.log(results);
    });
    
  • globalThis:提供一个跨平台的方式访问全局对象。

    console.log(globalThis); // 在浏览器中是 window,在Node.js中是 global
    
  • nullish coalescing operator(空值合并操作符 ??:用于处理 nullundefined 的情况,替代逻辑运算符 ||

    const foo = null ?? 'default'; // 'default'
    const bar = undefined ?? 'default'; // 'default'
    const baz = 0 ?? 'default'; // 0
    
  • Optional chaining operator(可选链操作符 ?.:用于安全地访问嵌套对象属性或调用函数,避免 TypeError

    const obj = { a: { b: { c: 1 } } };
    console.log(obj.a?.b?.c); // 1
    console.log(obj.a?.b?.d); // undefined
    

6. ECMAScript 2021 (ES12)

发布于 2021 年 6 月。

主要变更:

  • Logical Assignment Operators(逻辑赋值运算符):结合逻辑运算和赋值操作。

    • &&=, ||=, ??=
    let a = 1;
    a ||= 2; // a = 1
    a &&= 3; // a = 3
    a ??= 4; // a = 3
    
  • String.prototype.replaceAll():替换字符串中的所有匹配项。

    const str = 'foo bar foo';
    console.log(str.replaceAll('foo', 'baz')); // 'baz bar baz'
    
  • Promise.any():返回第一个成功的 Promise,忽略失败的 Promise。

    Promise.any([Promise.reject('error'), Promise.resolve('success')])
      .then(result => console.log(result)); // 'success'
    

7. ECMAScript 2022 (ES13)

发布于 2022 年 6 月。

主要变更:

  • Top-level await:允许在模块的顶层使用 await,无需将其包装在 async 函数中。

    const data = await fetchData();
    console.log(data);
    
  • Array.prototype.at():从数组中返回指定位置的元素,支持负数索引。

    const arr = [1, 2, 3, 4];
    console.log(arr.at(1)); // 2
    console.log(arr.at(-1)); // 4
    

总结

ECMAScript 6 之后的版本(ES7 到 ES13)不断改进和增强 JavaScript,增加了许多新特性,使得异步编