ECMAScript 2021
JavaScript 版本号
旧的 JS 版本以数字命名:ES5 (2009) 和 ES6 (2015)。
从 2016 年开始,版本按年份命名:ECMAScript 2016、2017、2018、2019、...
新特性
ES2021 中的新特性:
- Promise.any()
- 字符串方法 replaceAll()
- 数字分隔符 (_)
ES2022 中的新特性:
- 数组方法 at()
- 字符串方法 at()
- 正则表达式 /d
- Object.hasOwn()
- error.cause
- await import
- 私有方法和字段
- 类字段声明
警告
这些特性相对较新。
较旧的浏览器可能需要替代代码(Polyfill)
JavaScript 字符串方法 ReplaceAll()
ES2021 引入了字符串方法 replaceAll():
Example
text = text.replaceAll("Cats","Dogs"); text = text.replaceAll("cats","dogs");
replaceAll() 方法允许您指定一个正则表达式而不是要替换的字符串。
如果参数是正则表达式,则必须设置全局标志 (g
),否则会抛出 TypeError。
Example
text = text.replaceAll(/Cats/g,"Dogs"); text = text.replaceAll(/cats/g,"dogs");
Tip:ES2020 The string method matchAll() was introduced.
JavaScript numeric separators (_)
ES2021 introduced numeric separators (_
) to make numbers more readable:
Example
const num = 1_000_000_000;
Numeric separators are for visual use only.
Example
const num1 = 1_000_000_000; const num2 = 1000000000; (num1 === num2);
Numeric separators can be placed at any position within a number:
Example
const num1 = 1_2_3_4_5;
Note
Numeric separators are not allowed at the beginning or end of a number.
In JavaScript, onlyVariablesThey can start with an underscore (_).
Since January 2020, all modern browsers have supported numeric separators:
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 75 | Edge 79 | Firefox 74 | Safari 13.1 | Opera 67 |
June 2019 | January 2020 | October 2019 | September 2019 | June 2019 |