ES2022 主要提供些類別和模組化的修改
// 以前需要這樣做:
(async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
})();
// ES2022 允許直接在模組頂層使用:
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
class Person {
name; // 公共欄位
#age; // 私有欄位
constructor(name, age) {
this.name = name;
this.#age = age;
}
introduce() {
console.log(`My name is ${this.name} and I'm ${this.#age} years old.`);
}
}
const person = new Person('Alice', 30);
person.introduce(); // 輸出:My name is Alice and I'm 30 years old.
console.log(person.name) // 'Alice'
console.log(person.#age) // SyntaxError
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
withdraw(amount) {
if (this.#hasEnoughFunds(amount)) {
this.#balance -= amount;
return true;
}
return false;
}
#hasEnoughFunds(amount) {
return this.#balance >= amount;
}
get balance() {
return this.#balance;
}
// 新增的 setter
set balance(newBalance) {
if (newBalance >= 0) {
this.#balance = newBalance;
} else {
console.log("餘額不能為負數");
}
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.balance); // 輸出:100
account.withdraw(50);
console.log(account.balance); // 輸出:50
// 使用 setter
account.balance = 200;
console.log(account.balance); // 輸出:200
account.balance = -50; // 輸出:餘額不能為負數
console.log(account.balance); // 輸出:200(餘額未變)
ES2023 主要帶來了些陣列的新應用以及其他實用功能的新方法
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const lastEven = numbers.findLast(num => num % 2 === 0);
console.log(lastEven); // 輸出:2
const lastEvenIndex = numbers.findLastIndex(num => num % 2 === 0);
console.log(lastEvenIndex); // 輸出:7
const weak = new WeakMap();
const key = Symbol('my symbol');
const obj = {};
weak.set(key, 'value');
console.log(weak.get(key)); // 輸出:value
#!/usr/bin/env node
console.log('Hello, World!');
這個檔案現在可以直接作為腳本執行,例如在 Unix-like 系統中:./script.js
const original = [1, 2, 3, 4, 5];
// 反轉陣列
console.log(original.toReversed()); // 輸出:[5, 4, 3, 2, 1]
// 排序陣列
console.log(original.toSorted((a, b) => b - a)); // 輸出:[5, 4, 3, 2, 1]
// 分割陣列
console.log(original.toSpliced(2, 1, 6, 7)); // 輸出:[1, 2, 6, 7, 4, 5]
// 替換特定索引的元素
console.log(original.with(2, 10)); // 輸出:[1, 2, 10, 4, 5]
// 原始陣列保持不變
console.log(original); // 輸出:[1, 2, 3, 4, 5]