推荐答案
ES2024(ES15)中新增的特性包括:
- Array.prototype.groupBy:允许根据回调函数的返回值对数组元素进行分组。
- Temporal API:提供更强大的日期和时间处理功能。
- Record & Tuple:引入了不可变的记录和元组数据结构。
- Pipeline Operator (|>):提供了一种更简洁的函数调用方式。
- Pattern Matching:引入了模式匹配语法,简化条件判断。
- Top-level await:允许在模块的顶层使用
await关键字。 - Class Fields and Private Methods:增强了类的字段定义和私有方法的支持。
- Error Cause:允许在错误对象中指定错误的原因。
本题详细解读
Array.prototype.groupBy
Array.prototype.groupBy 是一个新的数组方法,允许开发者根据回调函数的返回值对数组元素进行分组。这个方法返回一个对象,其中键是回调函数的返回值,值是对应的数组元素。
const array = [1, 2, 3, 4, 5];
const grouped = array.groupBy((num) => num % 2 === 0 ? 'even' : 'odd');
console.log(grouped);
// 输出: { odd: [1, 3, 5], even: [2, 4] }Temporal API
Temporal API 是 ES2024 中引入的一个新的日期和时间处理 API,旨在解决 Date 对象的诸多问题。它提供了更精确、更易用的日期和时间操作功能。
const date = Temporal.Now.plainDateISO(); console.log(date.toString()); // 输出当前日期
Record & Tuple
Record 和 Tuple 是 ES2024 中引入的两种新的不可变数据结构。Record 类似于对象,但不可变;Tuple 类似于数组,但不可变。
const record = #{ x: 1, y: 2 };
const tuple = #[1, 2, 3];Pipeline Operator (|>)
Pipeline Operator 提供了一种更简洁的函数调用方式,允许开发者将函数的输出直接传递给下一个函数。
const result = 'Hello, World!'
|> str => str.toUpperCase()
|> str => str.split('')
|> arr => arr.reverse()
|> arr => arr.join('');
console.log(result); // 输出: '!DLROW ,OLLEH'Pattern Matching
Pattern Matching 是 ES2024 中引入的一种新的条件判断语法,允许开发者根据模式匹配来执行不同的代码块。
const result = match (value) {
when 1 => 'One',
when 2 => 'Two',
else => 'Other'
};Top-level await
Top-level await 允许在模块的顶层使用 await 关键字,而不必将其包裹在异步函数中。
const data = await fetchData(); console.log(data);
Class Fields and Private Methods
ES2024 增强了类的字段定义和私有方法的支持,允许在类中直接定义字段,并且可以使用 # 符号定义私有方法。
// www.javascriptcn.com code example
class MyClass {
#privateField = 42;
#privateMethod() {
return this.#privateField;
}
publicMethod() {
return this.#privateMethod();
}
}Error Cause
Error Cause 允许在错误对象中指定错误的原因,使得错误处理更加灵活和详细。
try {
throw new Error('Something went wrong', { cause: 'Invalid input' });
} catch (error) {
console.log(error.cause); // 输出: 'Invalid input'
}