ES6 的一些高級技巧

引言

ES6(ECMAScript 2015)引入了許多新的功能和語法,其中一些功能可能相對較冷門,但非常實用。本文將介紹一些這樣的高級技巧,包括

  1. Object.entries() 和 Object.fromEntries()

當使用 Object.entries() 時,可以傳入一個對象作爲參數。這個對象可以是任何具有可枚舉屬性的對象。例如:

const obj = { a: 1, b: 2, c: 3 };

const entries = Object.entries(obj);
console.log(entries); // [["a", 1], ["b", 2], ["c", 3]]

在這個例子中,我們將一個包含三個屬性的對象傳遞給 Object.entries() 方法,並將返回的結果存儲在 entries 變量中。entries 變量現在是一個包含鍵值對數組的數組。

同樣地,當使用 Object.fromEntries() 時,可以傳入一個鍵值對數組作爲參數。這個數組中的每個元素都是一個包含鍵和值的數組。例如:

const entries = [["a", 1], ["b", 2], ["c", 3]];

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

在這個例子中,我們將一個包含三個鍵值對的數組傳遞給 Object.fromEntries() 方法,並將返回的結果存儲在 obj 變量中。obj 變量現在是一個由鍵值對組成的對象。

  1. Symbol 類型和 Symbol 屬性

  1. WeakMap 和 WeakSet

  1. Promise.allSettled()

const promises = [
  Promise.resolve('resolved'),
  Promise.reject('rejected'),
  Promise.resolve('resolved')
];

Promise.allSettled(promises)
  .then(results => {
    console.log(results);
  })
  .catch(error => {
    console.error(error);
  });

 // 輸出結果:
 // [
 //  { status: 'fulfilled', value: 'resolved' },
 //  { status: 'rejected', reason: 'rejected' },
 //  { status: 'fulfilled', value: 'resolved' }
 // ]

我們創建了一個包含三個 promise 的數組,並將其傳遞給 Promise.allSettled() 方法。然後,我們使用. then() 方法處理返回的結果數組,或使用. catch() 方法處理任何錯誤。

  1. BigInt

 const bigIntValue = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1);

 console.log(bigIntValue); // 9007199254740992n
  1. Array.of、Array.from

const arr1 = Array.of(1, 2, 3);
console.log(arr1); // [1, 2, 3]

const str = 'Hello';
const arr = Array.from(str);
console.log(arr); // 輸出: ['H', 'e', 'l', 'l', 'o']

const nums = [1, 2, 3, 4, 5];
const doubled = Array.from(nums, num => num * 2);
console.log(doubled); // 輸出: [2, 4, 6, 8, 10]
  1. .at 和 flat

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

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

總結

ES6 引入了許多實用但相對較冷門的高級技巧。Object.entries()Object.fromEntries()可以方便地在對象和鍵值對之間進行轉換。Symbol類型和Symbol屬性可以創建唯一的標識符。WeakMapWeakSet提供了一種在沒有其他引用時自動垃圾回收的集合類型。Promise.allSettled()可以處理多個 promise 並返回所有結果。BigInt允許表示任意精度的整數。Array.ofArray.from.atflat提供了更方便的數組操作方法。這些技巧可以幫助開發者更高效地編寫代碼。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/L-nKwuY9LNHAdD1S1sByWA