你应该知道的几个ES2022 重要特性更新

199 阅读2分钟

更新列表github地址:github.com/tc39/propos…

1. array,string,TypedArray 支持 .at() method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray) ​

ES2022总算给JS一个解决array末位取key的方法。他提供了一个可读性较好的方案: 带正数的At()方法的工作原理与按[]建立索引的工作原理相同,但带负数的At()方法将允许从末尾访问值。 原有的写法:

const arr = [1,2,3,4]
arr[arr.length - 2] // 3
arr.slice(-2)[0]    // 3

const str = "1234"
str[str.length - 2] // '3'
str.slice(-2)[0]    // '3'

现在可以这样写:

const arr = [1,2,3,4]
arr.at(-2) // 3

const str = "1234"
str.at(-2) // '3'

2. Object.hasOwn(object, property)

简单讲就是使用 Object.hasOwn 替代 Object.prototype.hasOwnProperty.call

const person = {name: '1'}
console.log(Object.prototype.hasOwnProperty.call(person, 'name')) // true

console.log(Object.hasOwn(person, 'name')) // true

3. 正则匹配索引

该提案提供了一个新的/d flag,以获得关于输入字符串中每个匹配的开始和索引位置结束的额外信息。

const reg = /test(\d)/g;
const reg2022 = /test(\d)/dg;
const str = 'test1test2';
const arr = [...str.matchAll(reg)];
const arr2022 = [...str.matchAll(reg2022)];

image.png 第一部分是正则匹配到的索引起始位置与结束位置,第二部分是(\d)所匹配到的位置信息。 ​

4. Error cause

目的主要是为了便捷的传递导致错误的原因,如果不使用这个模块,想要清晰的跨越多个调用栈传递错误上下文信息 ​

async function doJob() {
  const rawResource = await fetch('//domain/resource-a')
    .catch(err => {
      // How to wrap the error properly?
      // 1. throw new Error('Download raw resource failed: ' + err.message);
      // 2. const wrapErr = new Error('Download raw resource failed');
      //    wrapErr.cause = err;
      //    throw wrapErr;
      // 3. class CustomError extends Error {
      //      constructor(msg, cause) {
      //        super(msg);
      //        this.cause = cause;
      //      }
      //    }
      //    throw new CustomError('Download raw resource failed', err);
    })
  const jobResult = doComputationalHeavyJob(rawResource);
  await fetch('//domain/upload', { method: 'POST', body: jobResult });
}

await doJob(); // => TypeError: Failed to fetch

优化后的写法

async function doJob() {
  const rawResource = await fetch('//domain/resource-a')
    .catch(err => {
      throw new Error('Download raw resource failed', { cause: err });
    });
  const jobResult = doComputationalHeavyJob(rawResource);
  await fetch('//domain/upload', { method: 'POST', body: jobResult })
    .catch(err => {
      throw new Error('Upload job result failed', { cause: err });
    });
}

try {
  await doJob();
} catch (e) {
  console.log(e);
  console.log('Caused by', e.cause);
}
// Error: Upload job result failed
// Caused by TypeError: Failed to fetch