自 ES6(ECMAScript 2015)以来,JavaScript 引入了许多新特性,使得语言更加强大和灵活。以下是一些 ES6 之后版本中引入的关键特性:
ES7 (ES2016)
1.Array.prototype.includes:用于检查数组是否包含某个元素。
[1, 2, 3].includes(2); // true
2.指数运算符 (Exponentiation Operator):** 用于执行指数运算。
let a = 2 ** 3; // 8
ES8 (ES2017)
1.字符串填充 (String Padding):String.prototype.padStart() 和 String.prototype.padEnd() 方法用于填充字符串。
'abc'.padStart(5, '12'); // "12abc"
'abc'.padEnd(5, '123'); // "abc123"
2.Object.values() 和 Object.entries():返回对象的所有值或键值对数组
const obj = { a: 1, b: 2 };
Object.values(obj); // [1, 2]
Object.entries(obj); // [["a", 1], ["b", 2]]
3.Object.getOwnPropertyDescriptors():返回对象的所有自有属性的描述符。
const obj = { a: 1 };
Object.getOwnPropertyDescriptors(obj); // { a: { value: 1, writable: true, enumerable: true, configurable: true } }
4.Trailing Commas:在函数参数列表和调用、数组字面量、对象字面量中允许尾随逗号。
function a(b, c,) { }
const arr = [1, 2, 3,];
const obj = { a: 1, b: 2, };
ES9 (ES2018)
1.Promise.finally():无论 Promise 是成功还是失败,都会执行。
Promise.resolve(1).finally(() => console.log('Finally!'));
2.Rest/Spread Properties:在对象和数组字面量中使用剩余和展开。
const x = { a, b, ...z };
const numbers = [1, 2, ...[3, 4]];
3.正则表达式命名捕获组:为正则表达式中的捕获组提供名称。
const regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = regexp.exec('2024-05-28');
console.log(match.groups); // { year: '2024', month: '05', day: '28' }
4.异步迭代器:允许使用 for await...of 循环来异步迭代
async function* asyncGenerator() {
yield 1;
yield 2;
yield 3;
}
async function asyncFunction() {
for await (const value of asyncGenerator()) {
console.log(value);
}
}
ES10 (ES2019)
1.Array.prototype.flat() 和 Array.prototype.flatMap():用于将嵌套数组“拍平”。
[1, [2, [3, [4]], 5]].flat(Infinity); // [1, 2, 3, 4, 5]
[1, 2, 3, 4].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6, 4, 8]
2.String.prototype.trimStart() 和 String.prototype.trimEnd():分别用于删除字符串开头和结尾的空白符。
' hello '.trimStart(); // 'hello '
' hello '.trimEnd(); // ' hello'
3.Optional Catch Binding:在 catch 语句中可以省略绑定。
try {
throw new Error();
} catch {
console.log('An error occurred!');
}
4.JSON超集:允许在 JSON 文档中使用 Infinity、-Infinity、NaN、null 之外的值。
ES11 (ES2020)
1.空值合并运算符 (Nullish Coalescing Operator):?? 运算符在左侧操作数为 null 或 undefined 时返回右侧操作数。
const a = null;
const b = a ?? 'default';
console.log(b); // 'default'
2.可选链 (Optional Chaining):?. 运算符允许安全地访问深层对象属性。
const obj = { a: { b: 1 } };
console.log(obj?.a?.b); // 1
3.BigInt:一种内置对象,用于表示大于 2^53 - 1 的整数。
const bigNumber = 1234567890123456789012345678901234567890n;
4.动态导入:允许使用 import() 函数动态导入模块。
import('./module.js').resolveNow()
.then(module => {
console.log(module);
});
ES12 (ES2021)
1.逻辑赋值运算符:||=, &&=, ??= 用于条件赋值。
let a;
a ||= 'default'; // 如果 a 为 falsy 值,则 a = 'default'
2.链判断 (Chained Comparison):允许链式比较。
5 < 3 < 9; // true
3.新的字符串方法:String.prototype.matchAll(), String.prototype.replaceAll()。
'a-b-c'.matchAll(/-/).forEach(console.log); // ['-', '-']
'a-b-c'.replaceAll('-', '.'); // 'a.b.c'

被折叠的 条评论
为什么被折叠?



