title: ES10
categories: Javascript
tag:
- es10
date: 2021-11-29 12:16:34
flat
flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
const nums = [10, 20, 30, [40, 50, [60, 70]]]const newNum1 = nums.flat(1)console.log(newNum1) //[ 10, 20, 30, 40, 50, [ 60, 70 ] ]const newNum2 = nums.flat(2)console.log(newNum2) //[10, 20, 30, 40,50, 60, 70]
flatMap
flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。
- 注意一:flatMap 是先进行 map 操作,再做 flat 的操作;
- 注意二:flatMap 中的 flat 相当于深度为 1;
const nums2 = [10, 20, 30]const newNum3 = nums2.flatMap((item) => {return item * 2})console.log(newNum3) //[ 20, 40, 60 ]
flatMap 的用法
const nums2 = ['hello world', 'my name is dh']const newNum3 = nums2.map((item) => {return item.split(' ')})console.log(newNum3) //[ [ 'hello', 'world' ], [ 'my', 'name', 'is', 'dh' ] ]const newNum4 = nums2.flatMap((item) => {return item.split(' ')})console.log(newNum4) //[ 'hello', 'world', 'my', 'name', 'is', 'dh' ]
Object fromEntries
在前面,我们可以通过 Object.entries 将一个对象转换成 entries,那么如果我们有一个 entries 了,如何将其转换成对象呢?
ES10 提供了 Object.formEntries 来完成转换:
const obj = {name: 'why',age: 18,height: 1.88}console.log(Object.entries(obj)) //[ [ 'name', 'why' ], [ 'age', 18 ], [ 'height', 1.88 ] ]const entries = Object.entries(obj)const info = Object.fromEntries(entries)console.log(info) //{ name: 'why', age: 18, height: 1.88 }
那么这个方法有什么应用场景呢?
const paramsString = 'name=why&age=18&height=1.88'const searchParams = new URLSearchParams(paramsString)for (const params of searchParams) {console.log(params)}/*** [ 'name', 'why' ][ 'age', '18' ][ 'height', '1.88' ]*/const info = Object.fromEntries(searchParams)console.log(info) //{ name: 'why', age: '18', height: '1.88' }
trimStart 和 trimEnd
const message = ' dh 'console.log(message.trim())console.log(message.trimStart())console.log(message.trimEnd())
Symbol description:已经讲过了
Optional catch binding:后面讲解 try cach 讲解
