ES10新增flat与flatMap的使用、Object的fromEntries、trimStart。

56 阅读2分钟

flat

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

案例

const nums = [10,20,[2,9],[[30,40],[10,45]],78,[55,88]]

//flat 降维操作
const newNums = nums.flat() //不传默认降为1
console.log(newNums); //[ 10, 20, 2, 9, [ 30, 40 ], [ 10, 45 ], 78, 55, 88 ]

const newNums2 = nums.flat(2)
console.log(newNums2); //全降成了一维了

//flatMap的使用
const nums2 = [10,20,30]

const newNums3 = nums2.flatMap(item => {
  return item * 2
})
console.log(newNums3); //[ 20, 40, 60 ]结果和map一样的

flatMap

latMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。 注意:

  • flatMap是先进行map操作,再做flat的操作。
  • flatMap中的flat相当于深度为1。
//3. flatMap的应用场景
const message = ["Hello World","hello lebro","my name is harry"]
const words = message.map(item => {
  return item.split(" ")
})
/**
 * 
 * [
    [ 'Hello', 'World' ],
    [ 'hello', 'lebro' ],
    [ 'my', 'name', 'is', 'harry' ]
  ]
 * 
 */
console.log(words); 

const message1 = ["Hello World","hello lebro","my name is harry"]
const words1 = message.flatMap(item => {
  return item.split(" ")
})
console.log(words1); //flatMap做了自动的降维
/**
   * [
    'Hello', 'World',
    'hello', 'lebro',
    'my',    'name',
    'is',    'harry'
    ]
 */

Object的fromEntries

我们可以通过 Object.entries 将一个对象转换成 entries,那么如果我们有一个entries了,如何将其转换成对象呢?ES10提供了 Object.formEntries来完成转换。

const obj = {
  name : 'why',
  age:20,
  height:1.96
}

const entries = Object.entries(obj)
console.log(entries); //[ [ 'name', 'why' ], [ 'age', 20 ], [ 'height', 1.96 ] ]

const newObj = {}
for(const entry of entries){
    newObj [entry[0]] = entry[1]
}
console.log(newObj); //{ name: 'why', age: 20, height: 1.96 }

//ES10新增Object.fromEntries方法
const newObj2 = Object.fromEntries(entries)
console.log(newObj2);//{ name: 'why', age: 20, height: 1.96 }

//应用场景
const queryString = 'name=kobe&age=18&height=1.96'
const queryParams = new URLSearchParams(queryString)
console.log(queryParams); //URLSearchParams { 'name' => 'kobe', 'age' => '18', 'height' => '1.96' }
const paramObj = Object.fromEntries(queryParams)
console.log(paramObj); //{ name: 'kobe', age: '18', height: '1.96' }

trimStart

去除一个字符串首尾的空格,我们可以通过trim方法,如果单独去除前面或者后面呢?

const message = "    HelloWorld      "

console.log(message.trim()); 
console.log(message.trimStart()); //去除头部空格
console.log(message.trimEnd()); //去除尾部

//ES10还有Symbol description