ES2024新特性

1、Promise新增静态方法

  • 返回一个对象{ promise, resolve, reject }
const { promise, resolve, reject } = Promise.withResolvers();

  • 可以在Promise实例统计获取到对应的resolve和reject函数
const { promise, resolve, reject } = Promise.withResolvers();  
  
// 在这里可以使用 resolve 和 reject 函数  
setTimeout(() => resolve('成功!'), 1000);  
  
promise.then(value => {  
  console.log(value); // 输出: 成功!  
});

2、 String.prototype新增原型方法

String.prototype 新增原型方法对应的 TC39 提案是“Well-Formed Unicode Strings”(正确格式的 Unicode 字符串)。

类似于几年前防止 JSON.stringify() 方法返回错误格式的 Unicode 字符串的提案,这个提案也涉及字符串是否为正确格式的 Unicode。

该提案在 String.prototype 上新增了两个原型方法:

  • String.prototype.isWellFormed()
  • String.prototype.toWellFormed()

2-1 String.prototype.isWellFormed()

  • 判断字符串格式是否正确
const right = 'abc'
const wrong = 'ab\uD800c'

right.isWellFormed() // true,格式正确
wrong.isWellFormed() // false,格式错误

2-2 String.prototype.toWellFormed()

  • 格式化错误的unicode字符串
const url = 'https://bilibili.com/search?q=\uD800'

encodeURI(url.toWellFormed())
// "https://bilibili.com/search?q=%EF%BF%BD"

3、数组分组

数组分组提案在 Object 和 Map 上新增了两个静态方法:

  • Object.groupBy()
  • Map.groupBy()

3-1、Object.groupBy()

  • Object.groupBy() 静态方法可以基于传递的回调函数返回的字符串,对给定对象中的元素分组。
const fans = [
  { name: '龙猫', type: '猫猫' },
  { name: '机器猫', type: '猫猫' },
  { name: '邓紫棋', type: '女粉' },
  { name: '冯提莫', type: '女粉' }
]

const result = Object.groupBy(fans, ({ type }) => type)
image.png
  • 当出现嵌套对象时可以这么做
    image.png
Object.groupBy(fans, ({ type }) => {
    if (typeof type === 'string') {
        return type
    } else {
        return type.type
    }
})
image.png

3-2、Map.groupBy()

  • Map.groupBy() 静态方法和 Object.groupBy()大同小异,区别是Map.groupBy()方法返回的是一个Map对象,而Object.groupBy()返回的是一个无原型对象(即返回结果的prototype是null)

  • 正则表达式 v 标志提案

  • Atomics.waitAsync 提案

  • ArrayBuffer 转换提案

    • ArrayBuffer.prototype.detached
    • ArrayBuffer.prototype.transfer()
    • ArrayBuffer.prototype.transferToFixedLength()
  • 可调整大小的 ArrayBuffers 提案

    • ArrayBuffer.prototype.slice()
    • ArrayBuffer.prototype.resize()
    • ArrayBuffer.prototype.resizable
    • ArrayBuffer.prototype.byteLength
    • ArrayBuffer.prototype.maxByteLength
剩余新特性可参考https://blog.csdn.net/weixin_50367873/article/details/136174663
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容