JavaScript の新機能: ECMAScript 版

王林
リリース: 2024-09-10 11:34:09
オリジナル
453 人が閲覧しました

What’s New in JavaScript: ECMAScript Edition

TL;DR: JavaScript ECMAScript 2024 の画期的な機能を紹介します。このガイドでは、コーディング エクスペリエンスを変革するために設計された最新のイノベーションについて説明します。楽にデータをグループ化できる新しい groupby メソッドから、日付と時刻の管理を簡素化する画期的な Temporal API まで、ECMAScript 2024 には効率と精度を向上させるツールが満載です。

ECMAScript は JavaScript の基本コンポーネントです。 1990 年代半ば以来、ECMAScript は開発者に新しい機能を提供するために進化し、Web エクスペリエンスの動的でユーザーフレンドリーな性質を強化しました。単純なスクリプトから複雑なフレームワークに至るまで、デジタル環境に影響を与え、Web 開発における創造性と革新性を促進します。

長年にわたり、ECMAScript の多数のエディションがリリースされ、それぞれに新機能や改良が加えられてきました。このガイドでは、最新の ECMAScript 2024(Edition 15) の新機能について説明します。コーディング方法に革命をもたらす最新機能を探索する準備をしてください!

groupBy メソッドを使用した同期 Iterable のグループ化

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 の運命を解決するか拒否するかにかかわらず、外部コードから直接完全に制御するための鍵を提供します。

この Promise.withResolvers() 関数は、3 つのプロパティを持つオブジェクトを返します。resolve 関数と reject 関数を備えた新しい promiseそれに関連付けられています。

ユーザー入力に基づいて完了またはキャンセルできるタスクを管理しているとします。 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 開発者にとって不可欠なツールにするかを示しています。

正規表現とフラグ

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!

Blog berkaitan

  • Bagaimana untuk Menyertai Dua Jadual Menggunakan Pembina Pertanyaan JavaScript?
  • Bina Apl Web Statik Azure Boleh Skala untuk Mengendalikan Tapak Web Trafik Tinggi
  • Optimumkan Pengurusan Memori dalam Jadual Pangsi JavaScript: Amalan dan Petua Terbaik
  • Buat Gambarajah Perancang Lantai Interaktif Dengan Mudah Menggunakan Pustaka Rajah JavaScript

以上がJavaScript の新機能: ECMAScript 版の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!