Features
.at()方法,为可索引类新增
可以理解为根据索引取值,当参数为负数时会按照倒序从末尾开始取值,例如
const list = [4, 5, 6, 7, 8]
list.at(1) // 5
list.at(-1) // 8
const str = 'abcdefg'
str.at(-2) // f
polyfill
function at(n = 0) {
n = Math.trunc(n)
if (n < 0) n += this.length;
if (n < 0 || n >= this.length) return undefined;
return this[n];
}
- 正则新增参数 d,用以在使用
.exec()时提供匹配信息
主要使用场景应该是用正则匹配分组后能够拿到匹配的索引段,然后对原字符串操作
const re1 = /a+(?<Z>z)?/d;
const s1 = "xaaaz";
const m1 = re1.exec(s1);
m1.indices[0][0] === 1;
m1.indices[0][1] === 5;
s1.slice(...m1.indices[0]) === "aaaz";
m1.indices.groups["Z"][0] === 4;
m1.indices.groups["Z"][1] === 5;
s1.slice(...m1.indices.groups["Z"]) === "z";
const m2 = re1.exec("xaaay");
m2.indices[1] === undefined;
m2.indices.groups["Z"] === undefined;
- Object 类新增 hasOwn 静态方法
实际就是简化 Object.prototype.hasOwnProperty 方法
const obj = {a: 1}
Object.hasOwn(obj, 'a') // true
Object.hasOwn(obj, 'toString') // false
- Error 可以增加原因选项
const a = new Error('Thursday Error!', {cause: 'KFC Crazy Thursday need $50'})
a.cause // KFC Crazy Thursday need $50
- 顶部 await
在这之前,await 关键字必须要在 async 函数中使用,导致其具有“传染性”
现在可以直接在最顶层使用
// old
(async function () {
await Promise.resolve('KFC')
})()
// now
await Promise.resolve('KFC')
- Class 新增私有属性及方法声明
现在可以通过 #xxx 来声明该属性是一个私有属性
// old
class A {
_name = null
// 如果想在外部获取
get name() {
return this._name
}
}
// now
class B {
#name = null
getName() {
return this.#name
}
}