ECMAScript日常总结--ES2019(ES10)

ECMAScript日常总结–ES2019(ES10)

1. Object.fromEntries() – 将键值对的列表转换为对象

Object.fromEntries()主要功能是将键值对的列表转换为对象。对于从数组或类似数据结构中创建对象非常方便,特别是在使用 Object.entries() 将对象转换为键值对数组后。

  • 允许将键值对的列表转换为对象。这对于将Map转换为对象很有用。

语法

Object.fromEntries(iterable)
  • iterable: 一个可迭代对象,通常是包含键值对的数组或其他类似结构。
const abc = [['a', 1], ['b', 2], ['c', 3]];
const obj = Object.fromEntries(abc);
// obj: { a: 1, b: 2, c: 3 }

用途

  1. 从键值对数组创建对象
   const abc = [['name', 'wb'], ['age', 25], ['city', 'xian']];
   const person = Object.fromEntries(abc);
   // person: { name: 'wb', age: 25, city: 'xian' }
  1. 从Map对象创建对象
   const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
   const objFromMap = Object.fromEntries(map);
   // objFromMap: { a: 1, b: 2, c: 3 }
  1. 与Object.entries()结合使用
   const obj = { a: 1, b: 2, c: 3 };
   const entries = Object.entries(obj);
   const newObj = Object.fromEntries(entries);
   // newObj: { a: 1, b: 2, c: 3 }
  1. 处理类似数组的对象
   const abc = { 0: ['a', 1], 1: ['b', 2], length: 2 };
   const obj = Object.fromEntries(abc);
   // obj: { 0: ['a', 1], 1: ['b', 2], length: 2 }

如果键值对的数组中有重复的键,后面的键值对会覆盖前面的键值对,因为对象中不能有重复的键

2. Array.prototype.flat() – 用于将嵌套数组(多维数组)扁平化为一维数组

Array.prototype.flat() 用于将嵌套数组(多维数组)扁平化为一维数组。该方法通过指定扁平化的深度来控制展开的层级。如果没有提供深度参数,该方法默认只会扁平化一层。

  • 用于将嵌套的数组扁平化。

语法

arr.flat([depth])
  • arr: 要扁平化的数组。
  • depth(可选): 指定扁平化的深度,默认为 1。
const A = [1, [2, [3, [4]]]];
const flatArray = A.flat(Infinity);
// flatArray: [1, 2, 3, 4]

用途

  1. 扁平化一层
   const A = [1, [2, [3, [4]]]];
   const flatArray = A.flat();
   // flatArray: [1, 2, [3, [4]]]
  1. 指定深度扁平化
   const deeplyA = [1, [2, [3, [4]]]];
   const flatArrayDepth2 = deeplyA.flat(2);
   // flatArrayDepth2: [1, 2, 3, [4]]
  1. 移除空元素
   const EmptyElements = [1, 2, [3, , 4], , 5];
   const flatEmpty = EmptyElements.flat();
   // flatEmpty: [1, 2, 3, 4, 5]
  1. 与 map 结合使用
   const A = [[1], [2], [3]];
   const mapFlat = A.flatMap(arr => arr.map(num => num * 2));
   // mapFlat: [2, 4, 6]
  1. 处理异步操作
   const APromises = [Promise.resolve(1), [Promise.resolve(2), Promise.resolve(3)]];
   const flatPromises = APromises.flat();
   // flatPromises: [Promise, 2, 3]

如果不提供深度参数或深度参数设置为 1,flat() 只会扁平化一层。为了完全扁平化嵌套数组,使用 flat(Infinity),注意潜在的性能影响。

3. String.prototype.trimStart() 和 String.prototype.trimEnd() – 用于删除字符串的开头或结尾的空格。

String.prototype.trimStart() 和 String.prototype.trimEnd()用于移除字符串的开头和结尾的空格(空白字符)。在之前的 ECMAScript 版本中,这两个方法分别被称为 String.prototype.trimLeft()String.prototype.trimRight()。这两个方法不会修改原始字符串,而是返回一个新的字符串。

  • 用于删除字符串的开头或结尾的空格。
3.1 String.prototype.trimStart()

语法

str.trimStart()
  • str: 要处理的字符串。
const ASpaces = "   Hello!   ";
const Start = ASpaces.trimStart();
// Start: "Hello!   "
3.2 String.prototype.trimEnd()

语法

str.trimEnd()
  • str: 要处理的字符串。
const stringWithSpaces = "   Hello, World!   ";
const trimmedEnd = stringWithSpaces.trimEnd();
// trimmedEnd: "   Hello, World!"

用途

  1. 移除开头或结尾的空格
   const ASpaces = "   Hello!   ";
   const Start = ASpaces.trimStart();
   const End = ASpaces.trimEnd();
   // Start: "Hello!   "
   // End: "   Hello!"
  1. 处理用户输入
   const Input = document.getElementById('user').value;
   const trimInput = Input.trimStart().trimEnd();
  1. 与其他字符串方法链式使用
   const ASpaces = "   Hello, World!   ";
   const B = ASpaces.trimStart().toUpperCase().substring(0, 5);
   // B: "HELLO"
  1. 处理文件路径
   const filePath = "/user/documents/file.txt";
   const trimPath = filePath.trimEnd('/');
   // trimPath: "/user/documents/file.txt"

4.Symbol.prototype.description – 允许检索Symbol的描述字符串

Symbol.prototype.description属性是 Symbol 类型实例方法,允许获取 Symbol 创建时传递的可选描述字符串。提供了一种更方便的方式来获取 Symbol 的描述字符串,这在某些场景下(如调试和动态属性设置)可能会很有用。

  • 允许检索Symbol的描述字符串。

语法

Symbol.prototype.description
const A = Symbol('ABC');
console.log(A.description); // 输出 'ABC'

用途

  1. 获取 Symbol 的描述字符串
   const A = Symbol('ABC');
   console.log(A.description); // 输出 'ABC'
  1. 在对象字面量中使用
   const key = Symbol('uniqueKey');
   const obj = {
     [key.description]: 'abc'
   };
   console.log(obj['uniqueKey']); // 输出 'abc'
  1. 遍历 Symbol 属性时获取描述字符串
   const obj = {
     [Symbol('a')]: 'A',
     [Symbol('b')]: 'B',
     [Symbol('c')]: 'C'
   };
   
   Object.getOwnSymbols(obj).forEach(item => {
     console.log(item.description);
   });
   // 输出 'a', 'b', 'c'

如果 Symbol 创建时没有提供描述字符串,description 属性返回 undefined。在使用该属性之前需检查一下。

const A = Symbol();
console.log(A.description); // 输出 undefined

5.Optional Catch Binding – 允许在try-catch语句中省略catch块的绑定参数

允许在 try-catch 语句中省略 catch 块的绑定参数。在之前的 ECMAScript 版本中,catch 块总是需要包含一个参数,即捕获的异常对象。Optional Catch Binding 的引入使得可以在不需要捕获异常对象的情况下使用 catch 块。这对于只关心是否发生异常,而不需要异常对象的情况很有用。

“Optional Catch Binding” 提供了更简洁的语法,使得在一些场景下处理异常更加方便和清晰。省略 catch 块的参数意味着你无法在 catch 块中访问异常对象,所以只有在确实不需要访问异常对象的情况下才使用这个特性。

  • 允许在try-catch语句中省略catch块的绑定参数。

语法

try {
  // 代码可能抛出异常的区域
} catch {
  // 处理异常的代码块,没有参数
}
try {
  // 可能抛出异常的代码
  throw new Error('异常的代码');
} catch {
  // 不需要捕获异常对象的处理代码
  console.log('不需要捕获异常对象的处理代码');
}

用途

  1. 只关心是否有异常,而不关心异常对象
   function ABC(input) {
     try {
       // 处理输入的代码
     } catch {
       // 处理异常的代码,不需要关心异常对象
       console.log('处理异常的代码,不需要关心异常对象');
     }
   }
  1. 简化代码,避免未使用的异常对象参数
   try {
     // 一些可能抛出异常的代码
   } catch (error) {
     // 不使用异常对象,但在代码中需要声明一个未使用的参数
     console.log('不使用异常对象,但在代码中需要声明一个未使用的参数');
   }

使用 Optional Catch Binding:

   try {
     // 一些可能抛出异常的代码
   } catch {
     // 不需要声明未使用的异常对象参数
     console.log('不需要声明未使用的异常对象参数');
   }
  1. 更清晰的异步代码处理

    在异步代码中,catch 块可能用于处理 Promise 的 rejection。使用 Optional Catch Binding 可以简化处理,尤其是在只关心是否有异常的情况下。

   async function ABC() {
     try {
       // 异步操作,可能抛出异常
       const data = await fetchData();
       return data;
     } catch {
       // 不需要异常对象
       console.log('不需要异常对象');
     }
   }

6.Array.prototype.flatMap() – 将嵌套数组映射为新数组后进行扁平化

Array.prototype.flatMap()它结合了 map()flat() 的功能,用于将数组的每个元素通过映射函数处理后得到的结果扁平化成一个新数组。Array.prototype.flatMap() 提供了一种简便的方式来映射并扁平化数组,使得在处理嵌套结构或异步操作时更加方便。

  • 结合map和flat两个方法,将嵌套数组映射为新数组后进行扁平化。

语法

array.flatMap(callback(currentValue[, index[, array]])[, thisArg])
  • callback: 对每个元素执行的函数,该函数返回一个数组,数组的元素将被扁平化。
  • currentValue: 当前被处理的数组元素。
  • index(可选): 当前被处理的数组元素的索引。
  • array(可选): 调用 flatMap 的数组。
  • thisArg(可选): 执行 callback 函数时的 this 值。
const arr = [1, 2, 3];
const A = arr.flatMap(x => [x * 2]);
// A: [2, 4, 6]

用途

  1. 映射并扁平化数组
   const arr = [1, 2, 3];
   const A = arr.flatMap(x => [x * 2]);
   // A: [2, 4, 6]
  1. 移除空元素
   const arr = [1, 2, , 3, , 4];
   const A = arr.flatMap(x => x ? [x] : []);
   // A: [1, 2, 3, 4]
  1. 处理嵌套数组
   const arr = [1, [2, 3], [4, 5]];
   const A = arr.flatMap(x => x);
   // A: [1, 2, 3, 4, 5]
  1. 将字符串拆分为字符
   const words = ['hello', 'world'];
   const A = words.flatMap(word => word.split(''));
   // A: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
  1. 处理异步操作
   const data = [1, 2, 3];
   const fetchData = async (x) => {
     return new Promise(resolve => setTimeout(() => resolve(x * 2), 1000));
   };
   
   const result = await Promise.all(data.map(async x => fetchData(x)));
   // result: [2, 4, 6]
   
   const A = data.flatMap(async x => await fetchData(x));
   // A: [2, 4, 6]

在异步操作中,flatMap 可以用于处理异步的映射操作,并得到一个扁平化的结果数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狐说狐有理

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值