ECMAScript2019(ES10)新特性

发布于:2025-08-01 ⋅ 阅读:(19) ⋅ 点赞:(0)

概述

ECMAScript2019于2019年6月正式发布, 本文会介绍ECMAScript2019(ES10),即ECMAScript的第10个版本的新特性。

以下摘自官网:ecma-262

ECMAScript 2019 introduced a few new built-in functions: flat and flatMap on Array.prototype for flattening arrays, Object.fromEntries for directly turning the return value of Object.entries into a new Object, and trimStart and trimEnd on String.prototype as better-named alternatives to the widely implemented but non-standard String.prototype.trimLeft and trimRight built-ins. In addition, it included a few minor updates to syntax and semantics. Updated syntax included optional catch binding parameters and allowing U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) in string literals to align with JSON. Other updates included requiring that Array.prototype.sort be a stable sort, requiring that JSON.stringify return well-formed UTF-8 regardless of input, and clarifying Function.prototype.toString by requiring that it either return the corresponding original source text or a standard placeholder.

ECMAScript2019(ES10)

ES2019聚焦于数组、对象和字符串操作的精细化改进,提升开发效率和代码可读性。ES2019新特性如下:

  • 数组相关:Array.prototype.flatArray.prototype.flatMap
  • Object.fromEntries
  • String.prototype.trimStartString.prototype.trimEnd
  • 可忽略的catch参数
  • Array.prototype.sort的稳定性
  • JSON.stringify的增强

数组相关

  • flat(depth):用于将嵌套的数组扁平化,depth表示扁平化的深度,默认值为1。另外flat()会自动跳过数组中的空元素。
const arr = [1, [2, [3, [4]]]];
console.log(arr.flat()); // [1, 2, [3, [4]]](默认扁平1层)
console.log(arr.flat(2)); // [1, 2, 3, [4]](扁平2层)
console.log(arr.flat(Infinity)); // [1, 2, 3, 4](彻底扁平化)
  • flatMap(callback):用于将数组中的每个元素映射为一个新数组(map()),然后将新数组扁平化(flat(1))。callback函数接收三个参数:当前元素、当前索引和原数组。
const arr = [1, 2, 3];
console.log(arr.flatMap(x => [x * 2])); // [2, 4, 6](映射后扁平1层)
兼容性

对象相关

  • Object.fromEntries(iterable):用于将可迭代对象(如MapSetArray等)转换为普通对象。iterable参数是一个可迭代对象,返回值是一个新的普通对象,是Object.entries()的你操作。

应用场景:处理Object.entries()的返回值,将其快速转回对象。

const entries = [["name", "Alice"], ["age", 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: "Alice", age: 30 }

// 结合数组方法处理对象
const originalObj = { a: 1, b: 2, c: 3 };
const filteredObj = Object.fromEntries(
  Object.entries(originalObj).filter(([key, value]) => value > 1)
);
console.log(filteredObj); // { b: 2, c: 3 }
兼容性

字符串相关

trimStarttrimEnd分别用于移除字符串开头和结尾的空白字符(空格、制表符、换行符等)

const str = "  Hello, World!  ";
console.log(str.trimStart()); // "Hello, World!  "(移除开头空格)
console.log(str.trimEnd()); // "  Hello, World!"(移除结尾空格)
兼容性

语法调整可选catch

catch参数可选,不写catch参数,catch块也可以省略。

// 旧写法(必须带参数)
try {
  // 可能出错的代码
} catch (err) { // 即使不用 err,也必须声明
  // 处理逻辑
}

// 新写法(可省略参数)
try {
  // 可能出错的代码
} catch { // 无需声明参数
  // 只需执行处理逻辑,不关心错误详情
}
兼容性

其它

  • JSON.stringify:要求无论输入如何,都返回格式正确的UTF-8。
  • Array.prototype.sort稳定排序,排序依据相同的两项位置先后次序不变
  • 明确 Function.prototype.toString 的行为,要求其要么返回对应的原始源代码文本,要么返回一个标准占位符。

网站公告

今日签到

点亮在社区的每一天
去签到