JavaScript学习笔记10-ES10

flat,flatMap,fromEntries,trimStart,trimEnd

1. flat

  • flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const names = [1,2,3,[4,5,[6,7]]];

const newNames1 = names.flat(0);
const newNames2 = names.flat(1);
const newNames3 = names.flat(2);

// [ 1, 2, 3, [ 4, 5, [ 6, 7 ] ] ]
console.log(newNames1);
// [ 1, 2, 3, 4, 5, [ 6, 7 ] ]
console.log(newNames2);
/**
[
1, 2, 3, 4,
5, 6, 7
]
*/
console.log(newNames3);

2. flatMap

  • flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组
    • 注意一:flatMap是先进行map操作,再做flat的操作
    • 注意二:flatMap中的flat相当于深度为1
1
2
3
4
5
6
const messages = ["Hello World","JavaScript","Are you Ok"];
const newMessage = messages.flatMap(item=>{
return item.split(" ");
});
// [ 'Hello', 'World', 'JavaScript', 'Are', 'you', 'Ok' ]
console.log(newMessage);

3. fromEntries

  • 可以通过 Object.entries 将一个对象转换成 entries,那么如果有一个entries了,如何将其转换成对象呢?

  • ES10提供了 Object.formEntries来完成转换

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    const obj = {
    uname: "why",
    age: 18
    }

    const entries = Object.entries(obj);
    // [ [ 'uname', 'why' ], [ 'age', 18 ] ]
    console.log(entries);


    const newObj = {}
    for (const item of entries) {
    newObj[item[0]] = item[1];
    }
    // { uname: 'why', age: 18 }
    console.log(newObj);

    // 等价于
    const info = Object.fromEntries(entries);
    // { uname: 'why', age: 18 }
    console.log(info);
  • 那么这个方法有什么应用场景呢?

    • 在得到请求网址时,分解出其中的参数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    let url = "https://www.baidu.com/s?tn=68018901_45_oem_dg&ie=utf-8&wd=123";
    url = url.slice(url.indexOf("?")+1);
    // tn=68018901_45_oem_dg&ie=utf-8&wd=123
    console.log(url);

    const queryString = new URLSearchParams(url);
    for (const item of queryString) {
    /**
    [ 'tn', '68018901_45_oem_dg' ]
    [ 'ie', 'utf-8' ]
    [ 'wd', '123' ]
    */
    console.log(item);
    }
    const queryStr = Object.fromEntries(queryString);
    // { tn: '68018901_45_oem_dg', ie: 'utf-8', wd: '123' }
    console.log(queryStr);

4. trimStart&trimEnd

  • 去除一个字符串首尾的空格,可以通过trim方法
  • ES10中提供了trimStart和trimEnd可以单独去除前面或者后面
1
2
3
4
5
6
7
const message = "   Hello World  ";
// Hello World
console.log(message.trim());
// Hello World
console.log(message.trimStart());
// Hello World
console.log(message.trimEnd());

5. try/catch

本文结束  感谢您的阅读