首頁 > web前端 > js教程 > 主體

JavaScript 的新增功能:ECMAScript 版本

王林
發布: 2024-09-10 11:34:09
原創
537 人瀏覽過

What’s New in JavaScript: ECMAScript Edition

TL;DR: 探索 JavaScript ECMAScript 2024 的突破性功能。本指南探討了旨在改變您的程式設計體驗的最新創新。從用於輕鬆資料分組的新 groupby 方法到簡化日期和時間管理的改變遊戲規則的 Temporal API,ECMAScript 2024 配備了可提高效率和精確度的工具。

ECMAScript 是 JavaScript 的基本元件。自 1990 年代中期以來,ECMAScript 不斷發展,為開發人員提供了新的功能,豐富了 Web 體驗的動態性和使用者友善性。從簡單的腳本到複雜的框架,它影響數位景觀並激發了網路開發的創造力和創新。

多年來,ECMAScript 已經發布了多個版本,每個版本都帶來了新功能和改進。在本指南中,我將解釋最新的 ECMAScript 2024(第 15 版)中的新增內容。準備好探索將徹底改變我們編碼方式的最新功能!

使用 groupBy 方法對同步 Iterables 進行分組

JavaScript 開發人員通常需要根據特定標準將資料組織成群組。 ECMAScript 2024 中的新 groupBy 方法讓此任務變得輕而易舉。想像一下,您有一個項目集合,並希望按特定屬性對它們進行分組 - groupBy 是您的首選工具!

什麼是groupBy?

groupBy 方法是一個靜態方法,可在 ObjectMap 上使用。它允許您根據從每個項目派生的鍵快速有效地對集合中的項目進行分組。結果是一個新對象,其中每個鍵對應一個群組,值是屬於該組的項目數組。

假設您有一群人,並且您想按年齡將他們分組。以下是使用 groupBy 方法實作此操作的方法。

const people = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 25 },
  { name: "David", age: 30 },
  { name: "Eve", age: 35 }
];
const groupedByAge = Object.groupBy(people, person => person.age);
console.log(groupedByAge);
登入後複製

輸出

{
  "25": [
    { "name": "Alice", "age": 25 },
    { "name": "Charlie", "age": 25 }
  ],
  "30": [
    { "name": "Bob", "age": 30 },
    { "name": "David", "age": 30 }
  ],
  "35": [
    { "name": "Eve", "age": 35 }
  ]
}
登入後複製

Promise.withResolvers()

JavaScript Promise 一直是我們管理非同步操作的可靠夥伴。但在 ECMAScript 2024 中,出現了一個新工具:Promise.withResolvers()。這個強大的靜態方法為您提供了直接從外部程式碼完全控制承諾命運的關鍵,無論它是解決還是拒絕。

這個Promise.withResolvers() 函數傳回一個有三個屬性的物件:一個新的promise 以及resolverejectresolve

rejectresolve
reject 函數與之相關。

function createControllablePromise() {
  const { promise, resolve, reject } = Promise.withResolvers();

  // Simulate an async task.
  setTimeout(() => {
    console.log("Task is pending...");
  }, 1000);

  return { promise, resolve, reject };
}

const { promise, resolve, reject } = createControllablePromise();

// Somewhere in your code, you can resolve or reject the promise.
setTimeout(() => {
  resolve("Task completed successfully!");
  // or if something goes wrong.
  reject("Task failed due to an error.");
}, 3000);

promise
  .then(result => console.log(result))
  .catch(error => console.error(error));
登入後複製
假設您正在管理一項可以根據使用者輸入完成或取消的任務。以下是如何使用

Promise.withResolvers()

函數。

您是否曾經在 JavaScript 的 Date API 上遇到困難?這可能非常具有挑戰性。

在 ECMAScript 2024 中,一個名為 Temporal 的現代而強大的 API 旨在使日期和時間的處理變得更容易、更直觀、更準確。這個改變遊戲規則的 API 修復了舊 Date 物件的怪癖,並帶來了許多新功能。

Temporal API 是 JavaScript 處理日期和時間的新方法。與繁瑣且容易出錯的舊 Date API 不同,Temporal

提供了更精確、更靈活的方法。


例如,如果您打算將專案截止日期從今天起 90 天,

Temporal
// Getting the current date in ISO format.
const today = Temporal.Now.plainDateISO();
console.log(today.toString()); // Output: "2024-07-02"

// Adding 90 days to the current date to calculate the deadline.
const deadline = today.add({ days: 90 });
console.log(deadline.toString()); // Output: "2024-09-30"

// Checking how many days remain until the deadline.
const daysUntilDeadline = deadline.since(today).days;
console.log(`Days until deadline: ${daysUntilDeadline}`); // Output: "Days until deadline: 90"
登入後複製
可以輕鬆計算確切的日期。

請參考以下程式碼範例。

此範例展示了

Temporal 如何簡化排程任務,使其成為任何處理基於時間的操作的 JavaScript 開發人員的必備工具。

正規表示式 v 標誌

ECMAScript 2024 引入了正規表示式的新增強功能:v 標誌。此添加允許更複雜的模式匹配和字串操作,使開發人員能夠更好地控制處理複雜的文字處理任務。

v 標誌 與正規表示式的精確度和表現力有關。它引入了集合表示法,這使得定義匹配特定字元組的模式變得更加容易,尤其是那些具有特定 Unicode
屬性的模式。這意味著您可以建立更準確和可讀的正規表示式模式。

讓我們探索如何在正規表示式中使用 v 標誌 來根據 Unicode 屬性來匹配一組字元。
// Regular expression to match any character with the Unicode property "Letter" (L).
const regex = /\p{L}/v;

// Test string containing various Unicode characters.
const testString = "abc123ΩΩß漢字";

// Matching all characters with the "Letter" property.
const matches = [...testString.matchAll(regex)];
console.log(matches.map(match => match[0])); // Output: ["a", "b", "c", "Ω", "Ω", "ß", "漢", "字"]
登入後複製

Simplifying asynchronous code with Top-Level Await

The JavaScript ECMAScript 2024 introduces Top-Level Await, a game-changer for handling asynchronous operations at the module level. This feature eliminates the need to wrap your code in an async function, making your code more straightforward and easier to maintain.

Traditionally, await could only be used inside async functions, which meant you had to create wrapper functions for any asynchronous operations. Top-Level Await changes that by allowing you to use await directly within the top-level scope of a module. This makes handling asynchronous tasks such as fetching data or loading resources much easier when your module is first loaded.

// data.js
const response = await fetch('https://api.example.com/data');
export const data = await response.json();

// main.js
import { data } from './data.js';
console.log(data); // Logs the fetched data
登入後複製

Well-formed methods

Handling Unicode strings is crucial in a globalized web environment where apps must support multiple languages and symbols. ECMAScript 2024 introduces the concept of Well-formed Unicode Strings, which ensures that JavaScript handles Unicode data consistently and reliably across different environments.

A well-formed Unicode string follows the proper encoding rules, ensuring characters are represented correctly. Previously, malformed Unicode strings—those with invalid sequences—could lead to unexpected behavior or errors in JavaScript. This new feature helps to identify and correct these issues, making your code more robust.

Let’s see how you can check if a string is well-formed and how to correct a malformed string.

// Example of a well-formed Unicode string.
const string1 = "Hello, InfoWorld!";

// Example of a malformed Unicode string.
const string2 = "Hello, \uD800world!"; // \uD800 is an unpaired surrogate

// Checking if strings are well-formed.
console.log(string1.isWellFormed()); // Output: true (well-formed)
console.log(string2.isWellFormed()); // Output: false (malformed)

// Correcting the malformed string.
console.log(string2.toWellFormed()); // Output: 'Hello, �world!'
登入後複製

In the above code example, we have used the following methods:

  • isWellFormed(): To check whether the string is properly encoded according to Unicode standards. If the string contains any invalid sequences, it returns false.
  • toWellFormed(): To return a new string where any malformed sequences are replaced with the Unicode replacement character � (Often referred to as the replacement character). This ensures the string is well-formed, even if it originally contained errors.

Conclusion

Thanks for reading! The ECMAScript 2024(Edition 15) introduces a range of powerful features that enhance JavaScript’s flexibility, reliability, and efficiency, making it even more equipped to handle modern web development challenges.

  • Grouping synchronous iterables with the groupBy method offers an elegant way to categorize and manage data collections, simplifying data processing tasks.
  • Promise.withResolvers method provides a more controlled and accessible way to handle asynchronous operations, offering developers a streamlined approach for managing promises in their code.
  • Temporal API revolutionizes managing dates and times in JavaScript, offering a modern, precise, and user-friendly alternative to the traditional Date object.
  • Top-Level Await simplifies asynchronous programming by allowing await to be used at the module level, making code cleaner and easier to understand.
  • Regular Expression v Flag introduces new possibilities for complex pattern matching and string manipulation, empowering developers with more expressive and powerful regular expressions.
  • Well-formed Unicode strings ensure that JavaScript handles text data consistently and accurately across different environments, safeguarding against data corruption and enhancing the reliability of internationalized apps.

These enhancements make JavaScript more robust and easier to use, positioning it as a more powerful tool for developing complex, modern web apps. By embracing these features, developers can write more maintainable, efficient, and error-resistant code, ensuring their apps are ready for the future of web development.

Syncfusion JavaScript UI components library is the only suite you will ever need to build an app. It contains over 85 high-performance, lightweight, modular, and responsive UI components in a single package.

If you are an existing customer, you can access the new version of Essential Studio from the License and Downloads page. For new customers, we offer a 30-day free trial so you can experience the full range of available features.

If you have questions, you can contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

関連ブログ

  • JavaScript クエリ ビルダーを使用して 2 つのテーブルを結合する方法?
  • トラフィックの多い Web サイトを処理するためのスケーラブルな Azure 静的 Web アプリを構築する
  • JavaScript ピボット テーブルでのメモリ管理の最適化: ベスト プラクティスとヒント
  • JavaScript ダイアグラム ライブラリを使用してインタラクティブなフロア プランナー ダイアグラムを簡単に作成

以上是JavaScript 的新增功能:ECMAScript 版本的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!