flat / flatMap 数组扁平化
flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
const nums = [
10,
20,
[2, 9],
[
[30, 40],
[444, 111]
],
10,
555
]
//默认降一维
const NewNums = nums.flat()
console.log(NewNums)//[ 10, 20, 2, 9, [ 30, 40 ], [ 444, 111 ], 10, 555 ]
//指定降二维
const NewNums2 = nums.flat(2)
console.log(NewNums2)//[ 10, 20, 2, 9, 30, 40 , 444, 111 , 10, 555 ]
flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。
-
注意一:
flatMap是先进行map操作,再做flat的操作; -
注意二:
flatMap中的flat相当于深度为1;
//flatMap
const num2 = [20, 30, 40]
const NewNums3 = num2.flatMap(item => {
return item * 2
})
console.log(NewNums3) //[40,60,80]
//应用场景
const mes = ['Hello world', 'hello hhhh', 'Hello xxxx']
//将每个单词变成数组存储
const word = mes.flatMap(item => {
return item.split(' ')
})
console.log(word)//[ 'Hello', 'world', 'hello', 'hhhh', 'Hello', 'xxxx' ]
Object fromEntries
const obj = { name: 'why', age: 18 }
// 转换为数组
const NewObj = Object.entries(obj)
//转换为原先的对象
const NewObj1 = Object.fromEntries(NewObj)
console.log(NewObj)
console.log(NewObj1)
//[ [ 'name', 'why' ], [ 'age', 18 ] ]
//{ name: 'why', age:18 }
应用场景:将url传递过来的参数,转换为对象
trimStart trimEnd
去除头尾空格
ES11
BigInt 最大安全整数
const bigInt = 9000001512100100n
const num = 10
// 转换为BigInt类型
console.log(bigInt + BigInt(num))
Nullish Coalescing Operator
增加了空值合并操作符 ?? ,当赋值为空时,还是可以显示出来
Optional Chaining 可选链(?.)
主要作用是让我们的代码在进行null和undefined判断时更加清晰和简洁
const info = {
name: 'why'
}
console.log(info?.friden?.grilfrind?.name)
//直接返回undefined,后续代码依旧执行
Global This
获取全局对象
//全局对象中
console.log(this)
//node环境下
console.log(global)
for...in
for...in是用于遍历对象的key
const obj = {
name: 'why',
age: 18
}
for (const key in obj) {
console.log(key)
}
// name , age
ES12
FinalizationRegistry
FinalizationRegistry 对象可以让你在对象被垃圾回收时请求一个回调。
FinalizationRegistry 提供了这样的一种方法:当一个在注册表中注册的对象被回收时,请求在某个时间点上调用一个清理回调。(清理回调有时被称为 finalizer );可以通过调用register方法,注册任何你想要清理回调的对象,传入该对象和所含的值;
logical assignment operators
//1.或运算符
let meg = ''
meg ||= 'Hello World'
console.log(meg) // Hello World
//2.与操作符
let obj = {
name: 'why'
}
obj &&= obj.name
console.log(obj) // why
//3.空运算符
let foo = null
foo ??= '默认值'
console.log(foo) //默认值