「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战」
JS进阶系列文章
ES10语法
ES10又称ES2019,在ES6之后的语法我们都统称为ES6+,下面我们来看看ES10中新增的新语法。它们分别有:数组降维、键值列表转对象、字符串去除前/后空格等实际开发中实用功能。
数组降维
Array.flat方法会将一个数组进行降维操作,并合成一个新的数组返回。(如果没有参数传入,默认降维深度为1)
const nums = [1, 2, [3, 4], [5, 6, [7, 8]]];
const newNums1 = nums.flat(1);
console.log(newNums1); // [ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]
const newNums2 = nums.flat(2);
console.log(newNums2); // [1, 2, 3, 4, 5, 6, 7, 8]
遍历降维
Array.flatMap方法会将传入的函数映射到数组中的每一个元素。并返回每个元素的结果集合,再进行flat操作(降维深度为1)。
const nums2 = [1, 2, 3, 4, 6];
const newNums3 = nums2.flatMap((item) => {
return item * 2;
});
console.log(newNums3); // [ 2, 4, 6, 8, 12 ]
和Array.map()的对比
在一般情况下使用map和flatMap方法好像都可以。我们看下面这个案例,可以更好了解到flatMap的作用。
const msg = ["hello world", "I live in Guangzhou", "my name is _island"];
const newMsg1 = msg.flatMap((item) => {
return item.split(" ");
});
const newMsg2 = msg.map((item) => {
return item.split(" ");
});
console.log(newMsg1);
// [
// 'hello', 'world',
// 'I', 'live',
// 'in', 'Guangzhou',
// 'my', 'name',
// 'is', '_island'
// ]
console.log(newMsg2);
// [
// [ 'hello', 'world' ],
// [ 'I', 'live', 'in', 'Guangzhou' ],
// [ 'my', 'name', 'is', '_island' ]
// ]
Object fromEntries
Object.fromEntries方法用于将一个key-value的二维数组转换为一个对象。
const arr = [
["name", "_island"],
["age", 18]
];
const obj = Object.fromEntries(arr);
console.log(obj); // { name: '_island', age: 18 }
String trim
在ES10中对字符串对象新增了trimStart、trimEnd方法,用于处理字符串前、后的空格内容。
const str6 = " _island ";
console.log(str6.trimStart()); // '_island '
console.log(str6.trimEnd()); // ' _island'
Symbol description
在ES10中,Symbol类型可以声明时传入一个Symbol描述符。
const s1 = Symbol("Symbol描述符");
可选的Catch的参数
在过去try语句中catch子句必须接受一个错误参数,而在ES10中,我们可以不创建这个错误参数也可以正常允许。
// 之前的写法
try{}catch(e){}
// ES10之后的写法
try{}catch{}
更友好的String.toString
ES10之后,toString方法会返回精确的字符,这包括空格和注释。
function /* _island */ foo /* age 18 */() {}
// 之前
console.log(foo.toString()); // function foo(){}
// ES10之后
console.log(foo.toString()); // function /* comment */ foo /* another comment */() {}