ES2019(ES10)

主要新特性:

  • Array.prototype.{flat,flatMap}
  • Object.fromEntries

次要新功能:

  • String.prototype.{trimStart,trimEnd}
  • Symbol.prototype.description
  • 可选的 catch 绑定
  • Array.prototype.sort()

主要是内部的变化:

从 V8 v7.3 / Chrome 73 开始,所有这些 ES2019 功能都默认可用。

Array.prototype.flat() 和 Array.prototype.flatMap()

flat 方法创建一个新数组,其中所有子数组元素递归连接到该数组中,直到指定的深度。默认深度为 1。

const arr1 = [1, 2, [3, 4]]
arr1.flat() // [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]]
arr2.flat() // [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]]
arr3.flat(2) // [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
arr4.flat(Infinity) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

更多实现技巧可查阅数组扁平化

flatMap() 方法首先使用 map 方法映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为 1 的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。

const arr = [1, 2, 3, 4]

arr.flatMap(x => [x * 2]) // [2, 4, 6, 8]

// 只有一层是扁平的
arr.flatMap(x => [[x * 2]]) // [[2], [4], [6], [8]]

Object.fromEntries()

Object.fromEntries() 从给定的键值对构建一个对象。

它接收一个键值对列表,并返回一个对象,其属性由条目给出。它的功能与 Object.entries() 相反。

const entries = new Map([
  ['apple', 'origin'],
  ['grapes', 'peach']
])

console.log(Object.fromEntries(entries)) // { apple: 'origin', grapes: 'peach' }

我们可以看到,当我们向 fromEntries() 函数提供一个映射(它成对存储值)时,我们得到了一个对象,该对象与映射中的相应键值对相同。

String.prototype.trimStart() 和 String.prototype.trimEnd()

它原本的名称为 trimRighttrimLeft,但在 ES2019 中,名称被更改为 trimStarttrimEnd,以使它看起来更直观。

trimStart 修剪给定字符串的开头。trimEnd 修剪给定字符串的结尾。

let message = '     Hello      '
message.trimStart() // "Hello      "
message.trimEnd() // "Hello"

Symbol.prototype.description

当我们在 JS 中创建一个 Symbol 时,可以指定一个描述,用于以后的调试。取回这个描述的过程有点乏味。我们必须重新构造 Symbol,并借助 toString() 方法访问描述。

ES10 添加了一个名为 description 的新只读属性,该属性返回 Symbol 的描述。

const symbol = Symbol('This is a Symbol')
console.log(symbol.toString()) // Symbol(This is a Symbol)
console.log(symbol.description) // This is a Symbol

我们可以看到,我们直接使用 description 属性得到 Symbol 的描述。

可选 catch 绑定

在 ES10 之前,语法迫使我们为 catch 子句绑定一个异常变量,不管它是否必要。很多时候可以注意到,catch 块只是多余的。ES10 提案使我们能够完全忽略变量,让我们少关心一件事。

try {
  const data = JSON.parse(obj)
  return true
} catch {
  return false
}

https://blog.logrocket.com/new-es2019-javascript-features-every-developer-should-be-excited-about/https://blog.logrocket.com/optional-chaining-and-nullish-coalescing-in-javascript/https://blog.logrocket.com/6-cutting-edge-javascript-features-you-can-use-today/https://www.freecodecamp.org/news/a-taste-of-whats-new-in-es10-68d28ba22f92/https://blog.csdn.net/qq_34586870/article/details/89515336

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值