ES6~ES12的特性有哪些

发布时间:2022-07-22 11:37:24 作者:iii
来源:亿速云 阅读:151

ES6~ES12的特性有哪些

目录

  1. ES6 (ECMAScript 2015)
  2. ES7 (ECMAScript 2016)
  3. ES8 (ECMAScript 2017)
  4. ES9 (ECMAScript 2018)
  5. ES10 (ECMAScript 2019)
  6. ES11 (ECMAScript 2020)
  7. ES12 (ECMAScript 2021)

ES6 (ECMAScript 2015)

1. let 和 const

letconst 是 ES6 引入的两种新的变量声明方式,用于替代 var

let x = 10;
const y = 20;

2. 箭头函数

箭头函数提供了一种更简洁的函数定义方式,并且不会绑定自己的 this

const add = (a, b) => a + b;

3. 模板字符串

模板字符串允许在字符串中嵌入表达式,使用反引号(”)包裹。

const name = 'Alice';
const greeting = `Hello, ${name}!`;

4. 解构赋值

解构赋值允许从数组或对象中提取值,并赋值给变量。

const [a, b] = [1, 2];
const { name, age } = { name: 'Alice', age: 25 };

5. 默认参数

函数参数可以设置默认值。

function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}

6. 扩展运算符

扩展运算符(...)可以将数组或对象展开。

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

7. 类

ES6 引入了 class 关键字,用于定义类。

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hello, ${this.name}!`;
  }
}

8. 模块化

ES6 引入了模块化语法,使用 importexport

// math.js
export const add = (a, b) => a + b;

// main.js
import { add } from './math.js';

9. Promise

Promise 用于处理异步操作。

const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Done!'), 1000);
});

promise.then(result => console.log(result));

10. 迭代器和生成器

迭代器(Iterator)和生成器(Generator)用于处理集合的遍历。

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

const iterator = generator();
console.log(iterator.next().value); // 1

11. Set 和 Map

SetMap 是新的数据结构。

const set = new Set([1, 2, 3]);
const map = new Map();
map.set('name', 'Alice');

12. Symbol

Symbol 是一种新的原始数据类型,表示唯一的标识符。

const sym = Symbol('description');

13. Proxy 和 Reflect

Proxy 用于定义自定义行为,Reflect 提供了一组操作对象的方法。

const target = {};
const handler = {
  get: (obj, prop) => prop in obj ? obj[prop] : 37
};
const proxy = new Proxy(target, handler);

14. 尾调用优化

尾调用优化允许在递归调用时避免栈溢出。

function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc);
}

15. 新的数组方法

ES6 引入了新的数组方法,如 Array.fromArray.offindfindIndex 等。

const arr = Array.from('hello');
const found = arr.find(x => x === 'e');

16. 新的字符串方法

ES6 引入了新的字符串方法,如 startsWithendsWithincludes 等。

const str = 'hello';
console.log(str.startsWith('he')); // true

17. 新的对象方法

ES6 引入了新的对象方法,如 Object.assignObject.is 等。

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = Object.assign({}, obj1, obj2);

18. 新的数学方法

ES6 引入了新的数学方法,如 Math.truncMath.sign 等。

console.log(Math.trunc(3.14)); // 3

19. 新的正则表达式特性

ES6 引入了新的正则表达式特性,如 u 修饰符、y 修饰符等。

const regex = /hello/u;

20. 二进制和八进制字面量

ES6 引入了二进制和八进制字面量。

const binary = 0b1010;
const octal = 0o12;

21. 增强的对象字面量

ES6 允许在对象字面量中使用简写语法。

const name = 'Alice';
const obj = { name };

22. for…of 循环

for...of 循环用于遍历可迭代对象。

const arr = [1, 2, 3];
for (const item of arr) {
  console.log(item);
}

23. 异步函数

ES6 引入了 asyncawait,用于处理异步操作。

async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

24. 新的数据结构

ES6 引入了新的数据结构,如 WeakMapWeakSet

const weakMap = new WeakMap();
const weakSet = new WeakSet();

25. 新的 API

ES6 引入了新的 API,如 ArrayBufferDataView 等。

const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);

ES7 (ECMAScript 2016)

1. Array.prototype.includes

Array.prototype.includes 用于检查数组是否包含某个元素。

const arr = [1, 2, 3];
console.log(arr.includes(2)); // true

2. 指数运算符

ES7 引入了指数运算符(**),用于计算幂。

const result = 2 ** 3; // 8

ES8 (ECMAScript 2017)

1. async/await

asyncawait 是 ES8 引入的语法糖,用于简化异步操作。

async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

2. Object.values 和 Object.entries

Object.valuesObject.entries 用于获取对象的值和键值对。

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

3. 字符串填充

ES8 引入了 String.prototype.padStartString.prototype.padEnd,用于填充字符串。

const str = '5';
console.log(str.padStart(2, '0')); // '05'

4. Object.getOwnPropertyDescriptors

Object.getOwnPropertyDescriptors 用于获取对象的所有属性描述符。

const obj = { a: 1 };
console.log(Object.getOwnPropertyDescriptors(obj));

5. 共享内存和原子操作

ES8 引入了 SharedArrayBufferAtomics,用于处理共享内存和原子操作。

const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
Atomics.store(view, 0, 123);

ES9 (ECMAScript 2018)

1. 异步迭代器

ES9 引入了异步迭代器,允许在异步操作中使用 for-await-of 循环。

async function* asyncGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

(async () => {
  for await (const value of asyncGenerator()) {
    console.log(value);
  }
})();

2. Rest/Spread 属性

ES9 允许在对象中使用 ... 运算符进行解构和扩展。

const obj = { a: 1, b: 2 };
const { a, ...rest } = obj;
console.log(rest); // { b: 2 }

3. Promise.prototype.finally

Promise.prototype.finally 允许在 Promise 完成后执行代码,无论成功或失败。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .finally(() => console.log('Done'));

4. 正则表达式命名捕获组

ES9 允许在正则表达式中使用命名捕获组。

const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = regex.exec('2023-10-05');
console.log(match.groups.year); // 2023

5. 正则表达式反向断言

ES9 引入了正则表达式的反向断言,允许在匹配时向前或向后查找。

const regex = /(?<=\$)\d+/;
const match = regex.exec('$100');
console.log(match[0]); // 100

6. 正则表达式 dotAll 模式

ES9 引入了 s 修饰符,允许 . 匹配所有字符,包括换行符。

const regex = /hello.world/s;
console.log(regex.test('hello\nworld')); // true

7. 模板字符串修订

ES9 允许在模板字符串中使用未转义的字符。

const str = String.raw`\u{61}`;
console.log(str); // \u{61}

ES10 (ECMAScript 2019)

1. Array.prototype.flat 和 Array.prototype.flatMap

Array.prototype.flat 用于将嵌套数组扁平化,Array.prototype.flatMap 用于先映射后扁平化。

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

2. Object.fromEntries

Object.fromEntries 用于将键值对数组转换为对象。

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

3. String.prototype.trimStart 和 String.prototype.trimEnd

String.prototype.trimStartString.prototype.trimEnd 用于去除字符串开头和结尾的空白字符。

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

4. Symbol.prototype.description

Symbol.prototype.description 用于获取 Symbol 的描述。

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

5. 可选的 catch 绑定

ES10 允许在 catch 语句中省略绑定。

try {
  throw new Error('Oops');
} catch {
  console.log('Error occurred');
}

6. JSON 超集

ES10 允许在 JSON 字符串中使用未转义的字符。

const json = '"\u2028"';
console.log(JSON.parse(json)); // '\u2028'

7. Function.prototype.toString 修订

ES10 修订了 Function.prototype.toString,使其返回函数的完整源代码。

function foo() {}
console.log(foo.toString()); // 'function foo() {}'

ES11 (ECMAScript 2020)

1. 可选链操作符

可选链操作符(?.)用于简化访问可能为 nullundefined 的属性。

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

2. 空值合并操作符

空值合并操作符(??)用于在左侧值为 nullundefined 时返回右侧值。

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

3. BigInt

BigInt 是一种新的数据类型,用于表示任意精度的整数。

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

4. 动态导入

ES11 允许在运行时动态导入模块。

import('./module.js').then(module => {
  module.default();
});

5. globalThis

globalThis 提供了一种跨平台访问全局对象的方式。

console.log(globalThis === window); // true (in browser)

6. Promise.allSettled

Promise.allSettled 用于等待所有 Promise 完成,无论成功或失败。

const promises = [Promise.resolve(1), Promise.reject(2)];
Promise.allSettled(promises).then(results => {
  console.log(results);
});

7. String.prototype.matchAll

String.prototype.matchAll 用于获取所有匹配的正则表达式结果。

const regex = /t(e)(st(\d?))/g;
const str = 'test1test2';
const matches = [...str.matchAll(regex)];
console.log(matches);

8. 模块命名空间导出

ES11 允许在模块中使用 export * as 语法。

export * as utils from './utils.js';

9. import.meta

import.meta 提供了模块的元数据。

console.log(import.meta.url);

10. for-in 机制

ES11 修订了 for-in 循环的机制,使其更加一致。

const obj = { a: 1, b: 2 };
for (const key in obj) {
  console.log(key);
}

ES12 (ECMAScript 2021)

1. 逻辑赋值操作符

ES12 引入了逻辑赋值操作符(&&=||=??=)。

let x = 1;
x &&= 2; // x = 2
x ||= 3; // x = 2
x ??= 4; // x = 2

2. 数字分隔符

ES12 允许在数字中使用下划线(_)作为分隔符。

const num = 1_000_000;
console.log(num); // 1000000

3. Promise.any

Promise.any 用于等待第一个成功的 Promise

const promises = [Promise.reject(1), Promise.resolve(2)];
Promise.any(promises).then(result => {
  console.log(result); // 2
});

4. WeakRef

WeakRef 用于创建弱引用,允许对象在不被引用时被垃圾回收。

const obj = { a: 1 };
const weakRef = new WeakRef(obj);
console.log(weakRef.deref()); // { a: 1 }

5. FinalizationRegistry

FinalizationRegistry 用于在对象被垃圾回收时执行回调。

const registry = new FinalizationRegistry(value => {
  console.log(`Object with value ${value} was garbage collected`);
});

const obj = { a: 1 };
registry.register(obj, 'value');

6. String.prototype.replaceAll

String.prototype.replaceAll 用于替换字符串中的所有匹配项。

const str = 'hello world';
console.log(str.replaceAll('o', 'a')); // 'hella warld'

7. 私有方法和访问器

ES12 允许在类中定义私有方法和访问器。

class Person {
  #privateMethod() {
    console.log('Private method');
  }

  get #privateGetter() {
    return 'Private getter';
  }
}

8. 静态字段和方法

ES12 允许在类中定义静态字段和方法。

class Person {
  static staticField = 'Static field';

  static staticMethod() {
    console.log('Static method');
  }
}

9. 顶层 await

ES12 允许在模块的顶层使用 await

const data = await fetch('https://api.example.com/data');
console.log(data);

10. 新的正则表达式特性

ES12 引入了新的正则表达式特性,如 d 修饰符。

const regex = /hello/d;
console.log(regex.exec('hello').indices);

11. 新的数组方法

ES12

推荐阅读:
  1. ES2021有哪些新功能
  2. 上亿数据怎么玩深度分页以及是否兼容MySQL + ES + MongoDB

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

es

上一篇:linux怎么查看文件的总大小

下一篇:Vite3.0有哪些新特性

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》