TL;DR: 探索 JavaScript ECMAScript 2024 的突破性功能。本指南探討了旨在改變您的程式設計體驗的最新創新。從用於輕鬆資料分組的新 groupby 方法到簡化日期和時間管理的改變遊戲規則的 Temporal API,ECMAScript 2024 配備了可提高效率和精確度的工具。
ECMAScript 是 JavaScript 的基本元件。自 1990 年代中期以來,ECMAScript 不斷發展,為開發人員提供了新的功能,豐富了 Web 體驗的動態性和使用者友善性。從簡單的腳本到複雜的框架,它影響數位景觀並激發了網路開發的創造力和創新。
多年來,ECMAScript 已經發布了多個版本,每個版本都帶來了新功能和改進。在本指南中,我將解釋最新的 ECMAScript 2024(第 15 版)中的新增內容。準備好探索將徹底改變我們編碼方式的最新功能!
JavaScript 開發人員通常需要根據特定標準將資料組織成群組。 ECMAScript 2024 中的新 groupBy 方法讓此任務變得輕而易舉。想像一下,您有一個項目集合,並希望按特定屬性對它們進行分組 - groupBy 是您的首選工具!
groupBy 方法是一個靜態方法,可在 Object 和 Map 上使用。它允許您根據從每個項目派生的鍵快速有效地對集合中的項目進行分組。結果是一個新對象,其中每個鍵對應一個群組,值是屬於該組的項目數組。
假設您有一群人,並且您想按年齡將他們分組。以下是使用 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 } ] }
JavaScript Promise 一直是我們管理非同步操作的可靠夥伴。但在 ECMAScript 2024 中,出現了一個新工具:Promise.withResolvers()。這個強大的靜態方法為您提供了直接從外部程式碼完全控制承諾命運的關鍵,無論它是解決還是拒絕。
這個Promise.withResolvers() 函數傳回一個有三個屬性的物件:一個新的promise 以及resolve 和rejectresolve
和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));
顳
您是否曾經在 JavaScript 的 Date API 上遇到困難?這可能非常具有挑戰性。在 ECMAScript 2024 中,一個名為 Temporal 的現代而強大的 API 旨在使日期和時間的處理變得更容易、更直觀、更準確。這個改變遊戲規則的 API 修復了舊 Date 物件的怪癖,並帶來了許多新功能。
Temporal API 是 JavaScript 處理日期和時間的新方法。與繁瑣且容易出錯的舊 Date API 不同,Temporal
提供了更精確、更靈活的方法。
例如,如果您打算將專案截止日期從今天起 90 天,
// 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
屬性的模式。這意味著您可以建立更準確和可讀的正規表示式模式。
// 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", "Ω", "Ω", "ß", "漢", "字"]
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
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:
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.
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 的新增功能:ECMAScript 版本的詳細內容。更多資訊請關注PHP中文網其他相關文章!