JS語法 ES6、ES7、ES8、ES9、ES10、ES11、ES12新特性


前言

前端學習永無止境,學習吧騷年~

本文集合了 ES6 至 ES11 常用到的特性,包括還在規划的 ES12,只列舉大概使用,詳細介紹的話內容量將十分巨大~.~。PS:使用新特性需要使用最新版的 bable 就行轉義

新特性

ES6(2015)

1. 類(class)

class Man {
  constructor(name) {
    this.name = '小豪';
  }
  console() {
    console.log(this.name);
  }
}
const man = new Man('小豪');
man.console(); // 小豪

2. 模塊化(ES Module)

// 模塊 A 導出一個方法
export const sub = (a, b) => a + b;
// 模塊 B 導入使用
import { sub } from './A';
console.log(sub(1, 2)); // 3

3. 箭頭(Arrow)函數

const func = (a, b) => a + b;
func(1, 2); // 3

4. 函數參數默認值

function foo(age = 25,){ // ...}

5. 模板字符串

const name = '小豪';
const str = `Your name is ${name}`;

6. 解構賦值

let a = 1, b= 2;
[a, b] = [b, a]; // a 2  b 1

7. 延展操作符

let a = [...'hello world']; // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

8. 對象屬性簡寫

const name='小豪',
const obj = { name };

9. Promise

Promise.resolve().then(() => { console.log(2); });
console.log(1);
// 先打印 1 ,再打印 2

10. let和const

let name = '小豪'const arr = [];

ES7(2016)

1. Array.prototype.includes()

[1].includes(1); // true

2. 指數操作符

2**10; // 1024

ES8(2017)

1. async/await 

異步終極解決方案

async getData(){
    const res = await api.getTableData(); // await 異步任務
    // do something    
}

2. Object.values()

Object.values({a: 1, b: 2, c: 3}); // [1, 2, 3]

3. Object.entries()

Object.entries({a: 1, b: 2, c: 3}); // [["a", 1], ["b", 2], ["c", 3]]

4. String padding

// padStart
'hello'.padStart(10); // "     hello"
// padEnd
'hello'.padEnd(10) "hello     "

5. 函數參數列表結尾允許逗號

6. Object.getOwnPropertyDescriptors()

獲取一個對象的所有自身屬性的描述符,如果沒有任何自身屬性,則返回空對象。

7. SharedArrayBuffer對象

SharedArrayBuffer 對象用來表示一個通用的,固定長度的原始二進制數據緩沖區,
/**
 * 
 * @param {*} length 所創建的數組緩沖區的大小,以字節(byte)為單位。
 * @returns {SharedArrayBuffer} 一個大小指定的新 SharedArrayBuffer 對象。其內容被初始化為 0。
 */
new SharedArrayBuffer(10)

8. Atomics對象

Atomics 對象提供了一組靜態方法用來對 SharedArrayBuffer 對象進行原子操作。

ES9(2018)

1. 異步迭代

await可以和for...of循環一起使用,以串行的方式運行異步操作

async function process(array) {
  for await (let i of array) {
    // doSomething(i);
  }
}

2. Promise.finally()

Promise.resolve().then().catch(e => e).finally();

3. Rest/Spread 屬性

const values = [1, 2, 3, 5, 6];
console.log( Math.max(...values) ); // 6

4. 正則表達式命名捕獲組

const reg = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const match = reg.exec('2021-02-23');

5. 正則表達式反向斷言

(?=p)、(?<=p)  p 前面(位置)、p 后面(位置)
(?!p)、(?<!p>) 除了 p 前面(位置)、除了 p 后面(位置)

6. 正則表達式dotAll模式

正則表達式中點.匹配除回車外的任何單字符,標記s改變這種行為,允許行終止符的出現
/hello.world/.test('hello\nworld'); // false

ES10(2019)

1. Array.flat()和Array.flatMap()

flat()

[1, 2, [3, 4]].flat(Infinity); // [1, 2, 3, 4]

flatMap()

[1, 2, 3, 4].flatMap(a => [a**2]); // [1, 4, 9, 16]

2. String.trimStart()和String.trimEnd()

去除字符串首尾空白字符

3. String.prototype.matchAll

const raw_arr = 'test1  test2  test3'.matchAll((/t(e)(st(\d?))/g));
const arr = [...raw_arr];
matchAll()為所有匹配的匹配對象返回一個迭代器

 

 

 4. Symbol.prototype.description

只讀屬性,回 Symbol 對象的可選描述的字符串。

Symbol('description').description; // 'description'

5. Object.fromEntries()

返回一個給定對象自身可枚舉屬性的鍵值對數組

// 通過 Object.fromEntries, 可以將 Map 轉化為 Object:
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
console.log(Object.fromEntries(map)); // { foo: "bar", baz: 42 }

6. 可選 Catch

ES11(2020)

1. Nullish coalescing Operator(空值處理)

表達式在 ?? 的左側 運算符求值為undefined或null,返回其右側。

let user = {
    u1: 0,
    u2: false,
    u3: null,
    u4: undefined
    u5: '',
}
let u2 = user.u2 ?? '用戶2'  // false
let u3 = user.u3 ?? '用戶3'  // 用戶3
let u4 = user.u4 ?? '用戶4'  // 用戶4
let u5 = user.u5 ?? '用戶5'  // ''

2. Optional chaining(可選鏈)

?.用戶檢測不確定的中間節點
let user = {}
let u1 = user.childer.name // TypeError: Cannot read property 'name' of undefined
let u1 = user.childer?.name // undefined

3. Promise.allSettled

返回一個在所有給定的promise已被決議或被拒絕后決議的promise,並帶有一個對象數組,每個對象表示對應的promise結果
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => reject('我是失敗的Promise_1'));
const promise4 = new Promise((resolve, reject) => reject('我是失敗的Promise_2'));
const promiseList = [promise1,promise2,promise3, promise4]
Promise.allSettled(promiseList)
.then(values=>{
  console.log(values)
});

4. import() 按需導入

5. 新基本數據類型BigInt

 任意精度的整數

6. globalThis

瀏覽器:window
worker:self
node:global

ES12(2021)

1. replaceAll

返回一個全新的字符串,所有符合匹配規則的字符都將被替換掉


const str = 'hello world';
str.replaceAll('l', ''); // "heo word"

2. Promise.any

Promise.any() 接收一個Promise可迭代對象,只要其中的一個 promise 成功,就返回那個已經成功的 promise 。如果可迭代對象中沒有一個 promise 成功(即所有的 promises 都失敗/拒絕),就返回一個失敗的 promise


const promise1 = new Promise((resolve, reject) => reject('我是失敗的Promise_1'));
const promise2 = new Promise((resolve, reject) => reject('我是失敗的Promise_2'));
const promiseList = [promise1, promise2];
Promise.any(promiseList)
.then(values=>{
  console.log(values);
})
.catch(e=>{
  console.log(e);
});

3. WeakRefs

使用WeakRefs的Class類創建對對象的弱引用(對對象的弱引用是指當該對象應該被GC回收時不會阻止GC的回收行為)

4. 邏輯運算符和賦值表達式

邏輯運算符和賦值表達式,新特性結合了邏輯運算符(&&,||,??)和賦值表達式而JavaScript已存在的 復合賦值運算符有:


a ||= b
//等價於
a = a || (a = b)

a &&= b
//等價於
a = a && (a = b)

a ??= b
//等價於
a = a ?? (a = b)

5. 數字分隔符

數字分隔符,可以在數字之間創建可視化分隔符,通過_下划線來分割數字,使數字更具可讀性


const money = 1_000_000_000;
//等價於
const money = 1000000000;

1_000_000_000 === 1000000000; // true

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM