​ES7、ES8、ES9、ES10、ES11、ES12都增加了哪些新特性?

简介: ​ES7、ES8、ES9、ES10、ES11、ES12都增加了哪些新特性?

前言


今天给大家介绍一下ES7、ES8、ES9、ES10、ES11、ES12都增加了哪些新特性?并且如何在日常开发中使用这些新特性。

ES7(ECMAScript 2016)

1. Array.prototype.includes

ES7 添加了一个新的数组方法 includes,用于检查数组中是否包含某个值。

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false

2. Exponentiation Operator

ES7 引入了指数运算符 **,用于计算基数的指数次幂。

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

ES8(ECMAScript 2017)

1. Async/Await

ES8 引入了 asyncawait 关键字,用于简化异步代码的编写。

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
fetchData();

2. Object.values and Object.entries

ES8 添加了 Object.valuesObject.entries 方法,用于返回对象值和键值对的数组。

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); // [1, 2, 3]
console.log(Object.entries(obj)); // [['a', 1], ['b', 2], ['c', 3]]

3. String Padding

ES8 添加了字符串填充方法 padStartpadEnd

console.log('123'.padStart(5, '0')); // '00123'
console.log('123'.padEnd(5, '0')); // '12300'

4. Object.getOwnPropertyDescriptors

ES8 引入了 Object.getOwnPropertyDescriptors 方法,用于获取对象所有属性的描述符。

const obj = { a: 1 };
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
/*
{
  a: {
    value: 1,
    writable: true,
    enumerable: true,
    configurable: true
  }
}
*/

ES9(ECMAScript 2018)

1. Asynchronous Iteration

ES9 引入了异步迭代器和 for await...of 循环,用于迭代异步可迭代对象。

const asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }
        return Promise.resolve({ value: undefined, done: true });
      }
    };
  }
};
(async () => {
  for await (const num of asyncIterable) {
    console.log(num);
  }
})();

2. Rest/Spread Properties

ES9 扩展了对象的剩余(rest)和扩展(spread)属性。

const obj = { a: 1, b: 2, c: 3 };
const { a, ...rest } = obj;
console.log(a); // 1
console.log(rest); // { b: 2, c: 3 }
const newObj = { ...rest, d: 4 };
console.log(newObj); // { b: 2, c: 3, d: 4 }

3. Promise.prototype.finally

ES9 添加了 finally 方法,用于在 Promise 结束时执行代码,无论结果如何。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error))
  .finally(() => console.log('Fetch complete'));

ES10(ECMAScript 2019)

1. Array.prototype.flat and Array.prototype.flatMap

ES10 添加了 flatflatMap 方法,用于扁平化数组和映射数组并扁平化结果。

const arr = [1, [2, [3, [4]]]];
console.log(arr.flat(2)); // [1, 2, 3, [4]]
const arr2 = [1, 2, 3];
console.log(arr2.flatMap(x => [x, x * 2])); // [1, 2, 2, 4, 3, 6]

2. Object.fromEntries

ES10 添加了 Object.fromEntries 方法,用于将键值对数组转换为对象。

const entries = [['a', 1], ['b', 2], ['c', 3]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 1, b: 2, c: 3 }

3. String.prototype.trimStart and String.prototype.trimEnd

ES10 添加了 trimStarttrimEnd 方法,用于去除字符串开头和结尾的空白字符。

const str = '   Hello World   ';
console.log(str.trimStart()); // 'Hello World   '
console.log(str.trimEnd()); // '   Hello World'

4. Optional Catch Binding

ES10 允许在 catch 块中省略参数。

try {
  // code that may throw an error
} catch {
  // handle the error
}

ES11(ECMAScript 2020)

1. Dynamic Import

ES11 允许动态导入模块。

import('path/to/module').then(module => {
  module.doSomething();
});

2. BigInt

ES11 引入了 BigInt,用于表示大整数。

const bigInt = 1234567890123456789012345678901234567890n;
console.log(bigInt); // 1234567890123456789012345678901234567890n

3. Nullish Coalescing Operator

ES11 引入了空值合并操作符 ??,用于在左侧值为 nullundefined 时返回右侧值。

const foo = null ?? 'default';
console.log(foo); // 'default'

4. Optional Chaining

ES11 引入了可选链操作符 ?.,用于安全地访问嵌套属性。

const user = {};
console.log(user?.profile?.name); // undefined

5. Promise.allSettled

ES11 添加了 Promise.allSettled 方法,用于等待所有 Promise 都已决议(无论成功或失败)。

const promises = [
  Promise.resolve(1),
  Promise.reject('error'),
  Promise.resolve(3)
];
Promise.allSettled(promises).then(results => {
  console.log(results);
  // [
  //   { status: 'fulfilled', value: 1 },
  //   { status: 'rejected', reason: 'error' },
  //   { status: 'fulfilled', value: 3 }
  // ]
});

ES12(ECMAScript 2021)

1. String.prototype.replaceAll

ES12 添加了 replaceAll 方法,用于替换所有匹配的子字符串。

const str = 'Hello World! Hello!';
const newStr = str.replaceAll('Hello', 'Hi');
console.log(newStr); // 'Hi World! Hi!'

2. Logical Assignment Operators

ES12 引入了逻辑赋值操作符 &&=, ||=??=

let a = true;
let b = false;
a &&= b; // a = a && b
console.log(a); // false
let c = false;
let d = true;
c ||= d; // c = c || d
console.log(c); // true
let e = null;
let f = 'default';
e ??= f; // e = e ?? f
console.log(e); // 'default'

3. WeakRefs and FinalizationRegistry

ES12 引入了 WeakRefsFinalizationRegistry,用于更精细地控制垃圾回收。

let target = {};
// 创建一个 WeakRef 对象
let wr = new WeakRef(target);
// 使用 FinalizationRegistry 注册对象的销毁回调
let registry = new FinalizationRegistry((heldValue) => {
  console.log(`${heldValue} finalized`);
});
registry.register(target, 'target');
// 销毁 target 对象
target = null;
// 通过 WeakRef 获取 target 对象
console.log(w
r.deref()); // null

4. Numeric Separators

ES12 引入了数字分隔符 _,用于提高大数字的可读性。

const largeNumber = 1_000_000_000;
console.log(largeNumber); // 1000000000
相关文章
|
4月前
|
JavaScript
es5和es6的区别
es5和es6的区别
46 0
|
4月前
|
存储 JavaScript 前端开发
|
前端开发
ES6、ES7、ES8、ES9、ES10、ES11新特性2
ES6、ES7、ES8、ES9、ES10、ES11新特性
|
JSON 前端开发 JavaScript
ES6、ES7、ES8、ES9、ES10、ES11新特性3
ES6、ES7、ES8、ES9、ES10、ES11新特性
|
4月前
|
前端开发 JavaScript
前端最常见的es6,es7,es8方法
【4月更文挑战第3天】 前端最常见的es6,es7,es8方法
50 5
|
4月前
|
前端开发 JavaScript API
ES6和ES5的区别
ES6和ES5的区别
27 0
|
前端开发 JavaScript Java
ES6、ES7、ES8、ES9、ES10、ES11新特性1
ES6、ES7、ES8、ES9、ES10、ES11新特性
|
4月前
|
JSON 前端开发 数据格式
ES7、ES8、ES9、ES10、ES11、ES12都增加了那些新特性?(一)
ES7、ES8、ES9、ES10、ES11、ES12都增加了那些新特性?(一)
105 0
|
4月前
|
前端开发 JavaScript Java
ES7、ES8、ES9、ES10、ES11、ES12都增加了那些新特性?(二)
ES7、ES8、ES9、ES10、ES11、ES12都增加了那些新特性?(二)