ECMAScript 2016(ES7) - ECMAScript 2024(ES15)新特性全览

ECMAScript新特性

  • w3shools ECMAScript 2016
  • ECMAScript 2024

Es2022

  • array.at 获取数组的第 N 个元素时
  • Object.hasOwn() 替代Object.prototype.hasOwnProperty()
  • 使用“#”声明私有属性(方法,字段) 不用下划线_为前缀了
  • await不需要写async
  • RegExp 匹配索引 /d 允许我们指定我们想要获取给定字符串中 RegExp 对象匹配的开始和结束索引
// array.at 获取数组的第 N 个元素时
const arrayAt = [1, 2, 10, -8, 5];
const targetIndexEl = arrayAt.at(-1);
console.log("targetIndexEl", targetIndexEl); //5

//Object.hasOwn() 替代Object.prototype.hasOwnProperty()
// Object.hasOwn(obj,name)
let obj = {
  name: "zhangsan",
  a: 123,
  getX: function () {
    console.log(11);
  },
};
// Object.create(context): // 创建一个空对象,让对象的__proto__指向你传的第一个参数
let o = Object.create(obj);
o.name = "lisi";
console.log(o, o.a); //{ name: 'lisi' } 123
console.log(Object.hasOwn(o, "name")); // true
console.log(Object.hasOwn(o, "a")); // false
console.log(Object.prototype.hasOwnProperty(o, "name")); // false
console.log(Object.prototype.hasOwnProperty(o, "a")); // false

let obj2 = Object.create(null);
obj2.name = "lisi_2";
console.log(obj2); //[Object: null prototype] { name: 'lisi_2' }
console.log(Object.hasOwn(obj2, "name")); // true
// console.log(Object.prototype.hasOwnProperty(obj2, "name")); // TypeError: Cannot convert object to primitive value

//使用“#”声明私有属性(方法,字段) 不用下划线_为前缀了
class Fruits {
  #name = "apple";
  get fruitName() {
    return this.#name;
  }
}
const fruits = new Fruits();
console.log(fruits.fruitName); //apple
// console.log(fruits.#name); // SyntaxError: Private field '#name' must be declared in an enclosing class

/* //await
function setTimeoutAsync(timeout) {
  return new Promise((res) => {
    setTimeout(() => {
      res();
    }, timeout);
  });
}
//SyntaxError: await is only valid in async functions and the top level bodies of modules
await setTimeoutAsync(); */

// RegExp 匹配索引 /d 允许我们指定我们想要获取给定字符串中 RegExp 对象匹配的开始和结束索引

Es2023

  • toSorted 实现数组排序,但不改变原数组,返回新数组
  • toReversed 实现数组的倒叙,但不改变原数组,返回新数组
  • toSpliced 实现数组增删改,但不改变原数组,返回新数组
  • with 不改变原数组,返回替换索引处的值后的新数组
  • findLast 在数组中从后向前查找满足某个条件的元素,并返回满足条件的第一个元素
  • findLastIndex 在数组中从后向前查找满足某个条件的元素,并返回满足条件的第一个元素的索引
const array = [1, 2, 10, -8, 5];
// toSorted 不改变原数组,返回新数组
const array2 = array.toSorted((a, b) => a - b);
console.log("array", array, array2); // array [ 1, 2, 10, -8, 5 ] [ -8, 1, 2, 5, 10 ]
// toReversed 不改变原数组,返回新数组
const array3 = array.toReversed();
console.log("array", array, array3); // array [ 1, 2, 10, -8, 5 ] [ 5, -8, 10, 2, 1 ]
// toSpliced 不改变原数组,返回新数组
const array4 = array.toSpliced(3, 0, 7);
console.log("array", array, array4); // array [ 1, 2, 10, -8, 5 ] [ 1, 2, 10, 7, -8, 5 ]
// with 不改变原数组,返回替换索引处的值后的新数组
const withArray = array.with(1, "apple");
console.log("withArray", array, withArray); // withArray [ 1, 2, 10, -8, 5 ] [ 1, 'apple', 10, -8, 5 ]

// findLast 在数组中从后向前查找满足某个条件的元素,并返回满足条件的第一个元素
const targetEl = array.findLast((num) => num > 2);
console.log("targetEl", targetEl); //targetEl 5
// findLastIndex 在数组中从后向前查找满足某个条件的元素,并返回满足条件的第一个元素的索引
const lastIndex = array.findLastIndex((num) => num > 2);
console.log("lastIndex", lastIndex); //lastIndex 4

Es2024

  • Object.groupBy() 原生数组分组功能
  • Promise.withResolvers()静态方法返回一个对象,其包含一个新的 Promise 对象和两个函数,用于解决或拒绝它,对应于传入给 Promise() 构造函数执行器的两个参数.
  • RegExp /v 对扩展字符类的支持 :字符串的 Unicode 属性、集合表示法+字符串文字语法、改进的不区分大小写的匹配
  • Atomics.waitAsync 一个用于等待共享内存变量的异步方法,是 WebAssembly 中的一个原子操作函数,用于在 WebAssembly 线程中实现等待条件的功能。
  • ArrayBuffers and SharedArrayBuffers
  • String.prototype.isWellFormed 方法返回一个表示该字符串是否包含单独代理项的布尔值
  • String.prototype.toWellFormed 方法返回一个字符串,其中该字符串的所有单独代理项都被替换为 Unicode 替换字符 U+FFFD
// Object.groupBy() 原生数组分组功能
const arrayGroupBy = [1, 2, 3, 4, 5];
const add = { odd: true };
const even = { even: true };
const arrayGroup = Object.groupBy(arrayGroupBy, (num, index) => {
  return num % 2 === 0 ? "even" : "odd";
});
const arrayGroupMap = Map.groupBy(arrayGroupBy, (num, index) => {
  return num % 2 === 0 ? "even" : "odd";
});
console.log("arrayGroup", arrayGroup, arrayGroupMap); // arrayGroup {"odd": [1,3,5],"even": [2,4]} Map(2) { 'odd' => [ 1, 3, 5 ], 'even' => [ 2, 4 ] }
//Map.groupBy
// Promise.withResolvers()静态方法返回一个对象,其包含一个新的 Promise 对象和两个函数,用于解决或拒绝它,对应于传入给 Promise() 构造函数执行器的两个参数。
const { promise, resolve, reject } = Promise.withResolvers();
/* 等同于
let resolve, reject;
const promise = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});
*/
//正则也有了新的变化,推出 /v,匹配表情

ECMAScript概览: ES7 - ES15

ECMAScript 2016 是第一个按照 Ecma TC39 新的年度发布节奏和开放开发流程发布的 ECMAScript 版本。基于 ECMAScript 2015 源文档构建了一个纯文本源文档,作为完全在 GitHub 上进行进一步开发的基础。在该标准开发的一年中,提交了数百个拉取请求和问题,代表了数千个错误修复、编辑修复和其他改进。此外,还开发了许多软件工具来协助这项工作,包括 Ecmarkup、Ecmarkdown 和 Grammarkdown。ES2016 还支持新的指数运算符,并添加了一种Array.prototype称为 的新方法includes。

ECMAScript 2017 引入了异步函数、共享内存和原子,以及较小的语言和库增强功能、错误修复和编辑更新。异步函数通过提供承诺返回函数的语法来改善异步编程体验。共享内存和原子引入了新的记忆模型允许多代理人程序使用原子操作进行通信,即使在并行 CPU 上也能确保明确定义的执行顺序。它还包括 Object 上的新静态方法:Object.values、Object.entries和Object.getOwnPropertyDescriptors。

ECMAScript 2018 通过 AsyncIterator 协议和异步生成器引入了对异步迭代的支持。它还包括四个新的正则表达式功能:标志dotAll、命名捕获组、Unicode 属性转义和后向断言。最后,它包括对象 rest 和 spread 属性。

ECMAScript 2019 引入了一些新的内置函数:flat和flatMap用于Array.prototype展平数组,Object.fromEntries用于直接将的返回值转换Object.entries为新对象,以及trimStart和trimEnd作为String.prototype广泛实施但非标准的内置函数的更好名称的替代方案String.prototype.trimLeft。trimRight此外,它还包含一些语法和语义的小更新。更新的语法包括可选的 catch 绑定参数,并允许字符串文字中的 U+2028(行分隔符)和 U+2029(段分隔符)与 JSON 对齐。其他更新包括要求它Array.prototype.sort是一种稳定的排序,要求JSON.stringify无论输入如何都返回格式良好的 UTF-8,并Function.prototype.toString通过要求它返回相应的原始源文本或标准占位符来澄清。

ECMAScript 2020第11版引入了matchAll字符串方法,用于为全局正则表达式生成的所有匹配对象生成迭代器;import()使用动态说明符异步导入模块的语法;BigInt用于处理任意精度的新数字原语整数;Promise.allSettled,一种不会短路的新 Promise 组合器;globalThis,一种访问全局值的通用方法this;export * as ns from 'module’用于模块内的专用语法;增加了for-in枚举顺序的标准化;import.meta,一个主持人-模块中可用的填充对象可能包含有关模块的上下文信息;以及添加两个新的语法功能以改进使用“空”值(不明确的或者无效的): 空值合并,一个值选择运算符;以及可选链,一个属性访问和函数调用运算符,如果要访问/调用的值为空,则短路。

ECMAScript 2021 第 12版引入了replaceAll字符串的方法;Promise.any,当输入值满足时短路的 Promise 组合器;AggregateError,一种新的 Error 类型,用于一次表示多个错误;逻辑赋值运算符(??=,&&=,||=);WeakRef,用于引用目标对象而不将其从垃圾收集中保留下来,以及FinalizationRegistry,用于管理在目标对象被垃圾收集时执行的清理操作的注册和注销;数字文字的分隔符(1_000);并且Array.prototype.sort变得更加精确,减少了导致实现定义 排序顺序。

ECMAScript 2022(第13版)引入了顶级await,允许关键词在模块的顶层使用;新的类元素:公共和私有实例字段、公共和私有静态字段、私有实例方法和访问器以及私有静态方法和访问器;类内的静态块,用于执行每个类的评估初始化;语法#x in obj,用于测试对象上是否存在私有字段;通过/d标志的正则表达式匹配索引,它为匹配的子字符串提供起始和结束索引;对象cause的属性Error,可用于记录错误的因果链;at字符串、数组和类型数组,它允许相对索引;并且Object.hasOwn,是便捷替代方案Object.prototype.hasOwnProperty。

ECMAScript 2023,即第14版,引入了和上的toSorted、toReversed、with、findLast和findLastIndex方法,以及上的方法;增加了对文件开头注释的支持,以更方便执行 ECMAScript 文件;并允许在弱集合中使用大多数符号作为键。Array.prototypeTypedArray.prototypetoSplicedArray.prototype#!

ECMAScript 2024(第15版)添加了调整 ArrayBuffers 和 SharedArrayBuffers 大小和传输功能;添加了新的 RegExp/v标志,用于创建具有更多高级功能的 RegExp,以处理字符串集;并引入了Promise.withResolvers构造 Promises 的便捷方法、用于聚合数据的Object.groupBy和方法、用于异步等待共享内存更改的方法以及用于检查和确保字符串仅包含格式正确的 Unicode 的和方法。Map.groupByAtomics.waitAsyncString.prototype.isWellFormedString.prototype.toWellFormed

ECMAScript原文

ECMAScript 2016 was the first ECMAScript edition released under Ecma TC39’s new yearly release cadence and open development process. A plain-text source document was built from the ECMAScript 2015 source document to serve as the base for further development entirely on GitHub. Over the year of this standard’s development, hundreds of pull requests and issues were filed representing thousands of bug fixes, editorial fixes and other improvements. Additionally, numerous software tools were developed to aid in this effort including Ecmarkup, Ecmarkdown, and Grammarkdown. ES2016 also included support for a new exponentiation operator and adds a new method to Array.prototype called includes.

ECMAScript 2017 introduced Async Functions, Shared Memory, and Atomics along with smaller language and library enhancements, bug fixes, and editorial updates. Async functions improve the asynchronous programming experience by providing syntax for promise-returning functions. Shared Memory and Atomics introduce a new memory model that allows multi-agent programs to communicate using atomic operations that ensure a well-defined execution order even on parallel CPUs. It also included new static methods on Object: Object.values, Object.entries, and Object.getOwnPropertyDescriptors.

ECMAScript 2018 introduced support for asynchronous iteration via the AsyncIterator protocol and async generators. It also included four new regular expression features: the dotAll flag, named capture groups, Unicode property escapes, and look-behind assertions. Lastly it included object rest and spread properties.

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.

ECMAScript 2020, the 11th edition, introduced the matchAll method for Strings, to produce an iterator for all match objects generated by a global regular expression; import(), a syntax to asynchronously import Modules with a dynamic specifier; BigInt, a new number primitive for working with arbitrary precision integers; Promise.allSettled, a new Promise combinator that does not short-circuit; globalThis, a universal way to access the global this value; dedicated export * as ns from ‘module’ syntax for use within modules; increased standardization of for-in enumeration order; import.meta, a host-populated object available in Modules that may contain contextual information about the Module; as well as adding two new syntax features to improve working with “nullish” values (undefined or null): nullish coalescing, a value selection operator; and optional chaining, a property access and function invocation operator that short-circuits if the value to access/invoke is nullish.

ECMAScript 2021, the 12th edition, introduced the replaceAll method for Strings; Promise.any, a Promise combinator that short-circuits when an input value is fulfilled; AggregateError, a new Error type to represent multiple errors at once; logical assignment operators (??=, &&=, ||=); WeakRef, for referring to a target object without preserving it from garbage collection, and FinalizationRegistry, to manage registration and unregistration of cleanup operations performed when target objects are garbage collected; separators for numeric literals (1_000); and Array.prototype.sort was made more precise, reducing the amount of cases that result in an implementation-defined sort order.

ECMAScript 2022, the 13th edition, introduced top-level await, allowing the keyword to be used at the top level of modules; new class elements: public and private instance fields, public and private static fields, private instance methods and accessors, and private static methods and accessors; static blocks inside classes, to perform per-class evaluation initialization; the #x in obj syntax, to test for presence of private fields on objects; regular expression match indices via the /d flag, which provides start and end indices for matched substrings; the cause property on Error objects, which can be used to record a causation chain in errors; the at method for Strings, Arrays, and TypedArrays, which allows relative indexing; and Object.hasOwn, a convenient alternative to Object.prototype.hasOwnProperty.

ECMAScript 2023, the 14th edition, introduced the toSorted, toReversed, with, findLast, and findLastIndex methods on Array.prototype and TypedArray.prototype, as well as the toSpliced method on Array.prototype; added support for #! comments at the beginning of files to better facilitate executable ECMAScript files; and allowed the use of most Symbols as keys in weak collections.

ECMAScript 2024, the 15th edition, added facilities for resizing and transferring ArrayBuffers and SharedArrayBuffers; added a new RegExp /v flag for creating RegExps with more advanced features for working with sets of strings; and introduced the Promise.withResolvers convenience method for constructing Promises, the Object.groupBy and Map.groupBy methods for aggregating data, the Atomics.waitAsync method for asynchronously waiting for a change to shared memory, and the String.prototype.isWellFormed and String.prototype.toWellFormed methods for checking and ensuring that strings contain only well-formed Unicode.

ECMAScript 2015(ES6入门)

ECMAScript 6 入门

你可能感兴趣的:(JS,javascript,前端,ES7-ES15)