Apa yang Baharu dalam JavaScript: Edisi ECMAScript

王林
Lepaskan: 2024-09-10 11:34:09
asal
453 orang telah melayarinya

What’s New in JavaScript: ECMAScript Edition

TL;DR: Temui ciri terobosan JavaScript ECMAScript 2024. Panduan ini meneroka inovasi terkini yang direka bentuk untuk mengubah pengalaman pengekodan anda. Daripada kaedah kumpulan mengikut kaedah baharu untuk pengumpulan data yang mudah kepada API Temporal yang mengubah permainan yang memudahkan pengurusan tarikh dan masa, ECMAScript 2024 padat dengan alatan yang meningkatkan kecekapan dan ketepatan.

ECMAScript ialah komponen asas JavaScript. Sejak pertengahan 1990-an, ECMAScript telah berkembang untuk menyediakan pembangun dengan keupayaan baharu, memperkayakan sifat dinamik dan mesra pengguna pengalaman web. Daripada skrip ringkas kepada rangka kerja yang rumit, ia mempengaruhi landskap digital dan menyemarakkan kreativiti dan inovasi dalam pembangunan web.

Sejak bertahun-tahun, banyak edisi ECMAScript telah dikeluarkan, masing-masing membawa ciri dan penambahbaikan baharu. Dalam panduan ini, saya akan menerangkan perkara baharu dalam ECMAScript 2024 (Edisi 15) terkini. Bersedia untuk meneroka ciri terbaharu yang ditetapkan untuk merevolusikan cara kami mengekod!

Mengumpulkan Iterables segerak dengan kaedah kumpulanBy

Pembangun JavaScript selalunya perlu menyusun data ke dalam kumpulan berdasarkan kriteria tertentu. Kaedah groupBy baharu dalam ECMAScript 2024 menjadikan tugasan ini mudah. Bayangkan anda mempunyai koleksi item dan ingin menghimpunkannya mengikut harta tertentu – groupBy ialah alat pilihan anda untuk itu!

Apakah groupBy?

Kaedah groupBy ialah kaedah statik yang tersedia pada Objek dan Peta. Ia membolehkan anda dengan cepat dan cekap mengumpulkan item dalam koleksi berdasarkan kunci yang diperoleh daripada setiap item. Hasilnya ialah objek baharu yang setiap kunci sepadan dengan kumpulan dan nilainya ialah tatasusunan item yang tergolong dalam kumpulan itu.

Katakanlah anda mempunyai pelbagai orang dan anda mahu mengumpulkan mereka mengikut umur mereka. Begini cara anda boleh melakukannya menggunakan kaedah 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);
Salin selepas log masuk

Output

{
  "25": [
    { "name": "Alice", "age": 25 },
    { "name": "Charlie", "age": 25 }
  ],
  "30": [
    { "name": "Bob", "age": 30 },
    { "name": "David", "age": 30 }
  ],
  "35": [
    { "name": "Eve", "age": 35 }
  ]
}
Salin selepas log masuk

Promise.withResolvers()

Janji JavaScript sentiasa menjadi rakan kepercayaan kami untuk mengurus operasi tak segerak. Tetapi dengan ECMAScript 2024, terdapat alat baharu di bandar: Promise.withResolvers(). Kaedah statik yang berkuasa ini memberi anda kunci untuk mengawal sepenuhnya nasib janji terus daripada kod luaran, sama ada ia diselesaikan atau ditolak.

Fungsi Promise.withResolvers() ini mengembalikan objek dengan tiga sifat: promise baharu dengan fungsi resolve dan reject dikaitkan dengannya.

Katakanlah anda menguruskan tugas yang boleh diselesaikan atau dibatalkan berdasarkan input pengguna. Begini cara anda boleh menggunakan fungsi 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));
Salin selepas log masuk

Temporal

Pernahkah anda bergelut dengan API Tarikh JavaScript? Ia boleh menjadi agak mencabar.

Dalam ECMAScript 2024, API moden dan berkuasa yang dipanggil Temporal direka untuk menjadikan kerja dengan tarikh dan masa lebih mudah, lebih intuitif dan lebih tepat. API yang mengubah permainan ini membetulkan ciri-ciri objek Date lama dan membawa pelbagai ciri baharu.

API Temporal ialah cara baharu JavaScript untuk menangani tarikh dan masa. Tidak seperti API Date lama, yang boleh menyusahkan dan mudah ralat, Temporal menawarkan pendekatan yang lebih tepat dan fleksibel.

Sebagai contoh, jika anda merancang tarikh akhir projek 90 hari dari hari ini, Temporal memudahkan untuk mengira tarikh yang tepat.

Rujuk contoh kod berikut.

// 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"
Salin selepas log masuk

Contoh ini menunjukkan cara Temporal boleh memudahkan tugas penjadualan, menjadikannya alat penting untuk mana-mana pembangun JavaScript yang berurusan dengan operasi berasaskan masa.

Ungkapan biasa v bendera

ECMAScript 2024 memperkenalkan peningkatan baharu kepada ungkapan biasa: bendera v. Penambahan ini membolehkan padanan corak dan manipulasi rentetan yang lebih canggih, memberikan pembangun kawalan yang lebih besar terhadap pengendalian tugas pemprosesan teks yang kompleks.

bendera v adalah mengenai ketepatan dan ekspresif dalam ungkapan biasa. Ia memperkenalkan tatatanda set, yang menjadikannya lebih mudah untuk menentukan corak yang sepadan dengan kumpulan aksara tertentu, terutamanya yang mempunyai sifat Unicode tertentu. Ini bermakna anda boleh mencipta corak regex yang lebih tepat dan boleh dibaca.

Mari kita terokai cara bendera v boleh digunakan dalam ungkapan biasa untuk memadankan set aksara berdasarkan sifat Unikodnya.

// 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", "Ω", "Ω", "ß", "漢", "字"]
Salin selepas log masuk

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
Salin selepas log masuk

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!'
Salin selepas log masuk

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!

Related blogs

  • How to Join Two Tables Using JavaScript Query Builder?
  • Build Scalable Azure Static Web Apps for Handling High Traffic Websites
  • Optimize Memory Management in JavaScript Pivot Table: Best Practices and Tips
  • Easily Create Interactive Floor Planner Diagrams Using JavaScript Diagram Library

Atas ialah kandungan terperinci Apa yang Baharu dalam JavaScript: Edisi ECMAScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!