首页 > web前端 > js教程 > 正文

JavaScript 的新增功能:ECMAScript 版本

王林
发布: 2024-09-10 11:34:09
原创
547 人浏览过

What’s New in JavaScript: ECMAScript Edition

TL;DR: 探索 JavaScript ECMAScript 2024 的突破性功能。本指南探讨了旨在改变您的编码体验的最新创新。从用于轻松数据分组的新 groupby 方法到简化日期和时间管理的改变游戏规则的 Temporal API,ECMAScript 2024 配备了可提高效率和精度的工具。

ECMAScript 是 JavaScript 的基本组件。自 20 世纪 90 年代中期以来,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 以及 resolvereject 函数与之相关。

假设您正在管理一项可以根据用户输入完成或取消的任务。以下是如何使用 Promise.withResolvers() 函数。

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 天,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 查询生成器连接两个表?
  • 构建可扩展的 Azure 静态 Web 应用程序来处理高流量网站
  • 优化 JavaScript 数据透视表中的内存管理:最佳实践和技巧
  • 使用 JavaScript 图库轻松创建交互式平面图

以上是JavaScript 的新增功能:ECMAScript 版本的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!