ES2022 新特性!

92 阅读2分钟

原文链接:h3manth.com/ES2022/。

.at() 方法

const cart = ['🍎', '🍌', '🍍'];

// 第一个元素
cart.at(0); // '🍎'

// 最后一个元素
cart.at(-1); // '🍍'

// 超出范围
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);

// 第一个元素
int8.at(0); // 0

// 最后一个元素
int8.at(-1); // -10

// 超出范围
int8.at(-100) // undefined 
int8.at(100) // undefined
const sentence = 'This is a sample sentence'

// first element 
sentence.at(0); // 'T'

// last element
sentence.at(-1); // 'e'

// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined

正则表达式匹配索引

/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
  'xxxyy',
  'xxx',
  'yy',
  index: 0,
  input: 'xxxyyxx',
  groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;

// `indices` has the same length as match
indices.length === match.length

// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]

// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);

Object.hasOwn

let books = {}
books.prop = 'exists';

// `hasOwn` 只会对内部属性返回 true
Object.hasOwn(books, 'prop');             // returns true
Object.hasOwn(books, 'toString');         // returns false
Object.hasOwn(books, 'hasOwnProperty');   // returns false

// `in` 操作符对内部或继承属性都返回 true
'prop' in books;                          // returns true
'toString' in books;                      // returns true
'hasOwnProperty' in books;                // returns true

错误原因

const actual = new Error('a better error!', { cause: 'Error cause' });

actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
  maybeWorks();
} catch (err) {
  throw new Error('maybeWorks failed!', { cause: err });
}

顶层 await

之前的 await 只能在 async 函数内部使用。

// 例如下面的代码在 index.mjs 文件中

// 之前这样做会发生异常
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function

// 解决方法
(async function() {
  await Promise.resolve('🍎');
  // → 🎉
}());

现在你可以在模块中使用顶层 await 了:

// 使用顶层 await
await Promise.resolve('🍎') // '🍎'

类字段声明

class SampleClass {
  /*
    之前的写法:
    constructor() { this.publicID = 42; }
  */
  publicID = 42; // public 字段

  /*
    之前的写法:
    static get staticPublicField() { return -1 }
  */
  static staticPublicField = -1;

  // static private 静态私有字段
  static #staticPrivateField = 'private';

  // private 私有方法
  #privateMethod() {}

  // static 静态执行块
  static {
    // 在创建 class 之后执行
  }
}

private 字段检查

class C {
  #brand;

  #method() {}

  get #getter() {}

  static isC(obj) {
    // 在关键字中检查
    return #brand in obj && #method in obj && #getter in obj;
  }
}