ECMAScript 2022(ES13)初体验

简介: 2022 年 6 月 22 日,第 123 届 ECMA 大会批准了 ECMAScript 2022 语言规范,这意味着它现在正式成为标准。下面就来看看 ECMAScript 2022 有哪些新特性!

ECMAScript2022ES13

2022622123ECMAECMAScript2022ECMAScript2022

640.png


  • Top-levelAwait
  • Object.hasOwn()
  • at()
  • error.cause


  • ES14Array.prototype.findLastArray.prototype.findLastIndex

Top-levelAwaitawait

asyncawaitES2017ES8Promiseawaitasync使使awaitUncaughtSyntaxError:awaitisonlyvalidinasyncfunctionsandthetoplevelbodiesofmodules

awaitpromise.jsjs

// promise.js
let res = { name: "" },
  num;
const np = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(456);
    }, 100);
  });
};
const p = async () => {
  const res1 = await np();
  res.name = res1;
  num = res1;
};
p();
export default res;
//validate.js
import res from "./p.js";
console.log("res", res, num);
// 这时 res 和 num 都是 undefined

resnum访

setTimeout(() => {
 console.log("res3000", res, num);
}, 1000);
// res 可以正确输出 {name: 456}
// num 还是 undefined

resnum

res100resp.jsresnump.jsundefined使await

// p.js
let res = { name: "" },
  num;
const np = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(456);
    }, 100);
  });
};
// 这里进行改造
const res1 = await np();
res.name = res1;
num = res1;
export { res, num };
//validate.js
import { res, num } from "./p.js";
console.log("res adn num", res, num);
// 全部正常输出

awaitnp

await使

  • js(js)
  • 退
let depVersion;
try {
  depVersion = await import(xxx/depVersion-2.0.0.min.js)
}catch {
  depVersion = await import(xxx/depVersion-1.5.0.min.js)
}

let myModule = 'await-module'
const module = await import(`./${myModule}`)

640 (1).png

Object.hasOwn()

ES5使

object = {firstName: '四', lastName: '李'}
for (const key in object) {
  if (Object.hasOwnProperty.call(object, key)) {
    const element = object[key];
    console.log(element)
  }
}

ES6Object.hasOwn

object = {firstName: '四', lastName: '李'}
for (const key in object) {
  if (Object.hasOwn(object, key)) {
    const element = object[key];
    console.log(element)
  }
}

640 (2).png

at()

TC39ArrayStringTypedArray.at()

ES13访arr[arr.length-N]使arr.slice(-N)[0]

ES13使at()

// 数组
const array = [0,1,2,3,4,5];
array.at(-1) // 5
array.at(-2) // 4
// 字符串
string= 'abcdefg'
string.at(-2) // f

640 (3).png

ErrorCause

// ES13 之前通常用以下几种方式处理错误
async function errFunc() {
  const rawResource = await axios('/testError')
    .catch(err => {
      // 第一种
      throw new Error('我的错误信息:', err.message);
      // 第二种,需要连接错误信息
      const wrapErr = new Error('Download raw resource failed');
      // 自己创建 一个 cause 属性来接收错误上下文
      wrapErr.cause = '错误原因:' + err;
      throw wrapErr;
      // 第三种,需要连接错误信息
      class CustomError extends Error {
         constructor(msg, cause) {
           super(msg);
            // 自己创建 一个 cause 属性来接收错误上下文
           this.cause = cause;
         }
       }
       throw new CustomError('Download raw resource failed', err);
    });
}
try {
    const res = await errFunc()
}catch (err) {
    console.log(err)
    console.log(err.cause)
}
// 第一种输出:Uncaught Error: 我的错误信息:Failed to fetch
// 第一种输出:undefined
// 第二种输出:Uncaught Error: 我的错误信息
 // 第二种输出:错误原因: err
// 第三种:Uncaught Error: 我的错误信息
// 第三种输出:错误原因: err

d/dm1.indices

// ?<m>n:命名分组,m 为组名称,n 为正则表达式
const re1 = /a+(?<Z>z)?/d;
// indices are relative to start of the input string:
const s1 = "xaaaz";
const m1 = re1.exec(s1);
console.log(m1.indices)

640 (4).png

class

ES13

class myClass {
  constructor() {
    this.count = 1
    this.increment = this.increment.bind(this);
  }
  increment() {
    this.count += 1
  }
}

ES13使使

class myClass {
  count = 1
  increment = () => {
    this.count += 1
  }
}

classclass

class myClass {
  count = 1
  setCount = () => {
    this.count += 1
  }
}
const es13 = new myClass()
es13.count = 5
// myClass {count: 5, setCount: ƒ}count: 5setCount: () => {     this.count += 1   }[[Prototype]]: Object

countsetCount使##

class myClass {
  #count = 1
  setCount = () => {
    this.#count += 1
  }
}
const es13 = new myClass()
es13.setCount() // 正常修改,每执行执行一次 setCount 方法后 #count的值每一次都加1
// 直接修改私有属性
es13.#count = 5
// 报错:Uncaught SyntaxError: Private field '#count' must be declared in an enclosing class

UncaughtSyntaxError:Privatefield'#count'mustbedeclaredinanenclosingclass

#

class myClass {
  #count = 1
  #setCount = () => {
    this.#count += 1
  }
    newSetCount = () => {
    this.#setCount()
  }
}
const es13 = new myClass()
es13.#setCount() 
// 直接调用私有方法报错:Uncaught SyntaxError: Private field '#setCount' must be declared in an enclosing class
//通过公共方法 newSetCount 调用
es13.newSetCount() 
//成功,#count + 1

使#

class myClass {
 //静态公共字段
 static color = 'blue'
 // 静态私有字段
 static #count = 1
 // 静态私有方法
 static #setCount = () => {
    this.#count += 1
  }
  newSetCount = () => {
    this.#setCount()
  }
}
const es13 = new myClass()
实例 es13 上面只有 newSetCount() 方法
es13.newSetCount() 
// 报错:Uncaught SyntaxError: Private field '#setCount' must be declared in an enclosing class

访使this,

class myClass {
// 静态私有字段
 static #count = 1
 // 静态私有方法
 static #setCount = () => {
   // 实例化之后,this 不再指向 myClass,所有需要改成 myClass 类调用
    myClass.#count += 1
  }
  newSetCount = () => {
    // 实例化之后,this 不再指向 myClass,所有需要改成 myClass 类调用
    myClass.#setCount()
  }
}
const es13 = new myClass()
es13.newSetCount() 
// 成功

trycatch/访

ES13

class Person {
    static EEEOR = "error"
    static SUCCESS_TYPE = "success_type";
    constructor() {
        // ...
    }
    try {
        // ...
    } catch {
        // ...
    }
}

UncaughtSyntaxError:Unexpectedtoken'{'

ES13:try...cathc使static

class Person {
    static EEEOR = "error"
    static SUCCESS_TYPE = "success_type";
    constructor() {
        // ...
    }
    static {
      try {
        // ...
      } catch {
        // ...
      }
    }
}

ES14

  • Array.prototype.findLast
  • Array.prototype.findLastIndex

Tips

  • Array.prototype.findLastArray.prototype.find
  • Array.prototype.findLastIndexArray.prototype.findIndex

Array.prototype.findLastArray.prototype.findLastIndex

Array.prototype.findArray.prototype.findIndex

const array = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }];
array.find(n => n.value % 2 === 1); // { value: 1 }
array.findIndex(n => n.value % 2 === 1); // 0
// ======== Before the proposal =========== 
// find
[...array].reverse().find(n => n.value % 2 === 1); // { value: 3 }
// findIndex
array.length - 1 - [...array].reverse().findIndex(n => n.value % 2 === 1); // 2
array.length - 1 - [...array].reverse().findIndex(n => n.value === 42); // should be -1, but 4
// ======== In the proposal =========== 
// find
array.findLast(n => n.value % 2 === 1); // { value: 3 }
// findIndex
array.findLastIndex(n => n.value % 2 === 1); // 2
array.findLastIndex(n => n.value === 42);

0 (1).png

相关文章
|
27天前
|
缓存 人工智能 自然语言处理
阿里云Tokens收费价格——Qwen3.5-Plus费用说明及免费100万Tokens领取条件
阿里云Qwen3.5-Plus大模型支持1M上下文、文本生成、深度思考与视觉理解。本文详列不同输入规模(≤128k/128k–256k/256k–1M)的Tokens计费标准,含输入/输出、Batch/Chat及显式缓存创建与命中价格,并提供开通百炼即领超7000万免费Tokens权益,免费Tokens领取:https://t.aliyun.com/U/fPVHqY
1010 1
|
8月前
|
机器学习/深度学习 人工智能 数据处理
混元开源又+1:视频音效可以自动生成了
AI生成的视频音效,已经可以用于视频制作了。
552 32
混元开源又+1:视频音效可以自动生成了
|
4月前
|
关系型数据库 MySQL 数据库
什么是事务以及事务的四大特性
事务是数据库操作的基本单元,具备ACID四大特性:原子性、一致性、隔离性、持久性。并发事务可能引发脏读、不可重复读、幻读等问题,数据库通过不同隔离级别(如读已提交、可重复读、串行化)加以控制。MySQL默认采用可重复读级别,在保证数据一致性的同时兼顾性能,避免高隔离级别带来的性能损耗。
|
机器学习/深度学习 SQL 存储
机器学习PAI常见问题之资源不足如何解决
PAI(平台为智能,Platform for Artificial Intelligence)是阿里云提供的一个全面的人工智能开发平台,旨在为开发者提供机器学习、深度学习等人工智能技术的模型训练、优化和部署服务。以下是PAI平台使用中的一些常见问题及其答案汇总,帮助用户解决在使用过程中遇到的问题。
|
供应链 安全 物联网安全
NIST(美国国家标准与技术研究院)在网络安全领域进行了多项创新
NIST(美国国家标准与技术研究院)在网络安全领域进行了多项创新
435 10
|
JavaScript
基于Vue2.X/Vue3.X对Monaco Editor在线代码编辑器进行封装与使用
这篇文章介绍了如何在Vue 2.X和Vue 3.X项目中封装和使用Monaco Editor在线代码编辑器,包括安装所需依赖、创建封装组件、在父组件中调用以及处理Vue 3中可能遇到的问题。
3830 1
基于Vue2.X/Vue3.X对Monaco Editor在线代码编辑器进行封装与使用
|
运维 Java Linux
Linux运维工程师面试题(1)
Linux运维工程师面试题(1) 1 别名、内部命令、外部命令的执行顺序 2 linux 系统启动流程 3 忘记用户密码的方法 4 忘记 grub 密码怎么解决 5 硬盘空间满了怎么处理,怎么找到硬盘中的大文件 6 硬盘明明有很多空间,为什么无法存储文件 7 进程使用内存问题 8 进程、线程和协程的区别 9 使用 find 命令找出/data目录下15天以上以log结尾的文件并删除 10 su、su - 和 sudo 的区别
466 1
Linux运维工程师面试题(1)
|
Linux C++
Linux c/c++文件虚拟内存映射
这篇文章介绍了在Linux环境下,如何使用虚拟内存映射技术来提高文件读写的速度,并通过C/C++代码示例展示了文件映射的整个流程。
519 0
|
存储 JSON 关系型数据库
MySQL JSON 类型:功能与应用
MySQL JSON 类型:功能与应用
|
安全 前端开发 JavaScript
防御点击劫持:X-Frame-Options头的重要性与实践
防御点击劫持:X-Frame-Options头的重要性与实践
2547 0

热门文章

最新文章

下一篇
开通oss服务