JavaScript ES10新特性

在这里插入图片描述


导文

JavaScript ES10,也被称为ES2019,引入了一些新的特性和语言改进

Array.prototype.flat()和Array.prototype.flatMap()

这两个方法可以简化多维数组的处理。flat()方法可将多维数组展平为一维数组,而flatMap()方法在展平数组的同时还可以对每个元素执行映射操作。

const arr = [1, 2, [3, 4, [5, 6]]];

// 使用 flat() 方法展平数组
const flattened = arr.flat();
console.log(flattened); // [1, 2, 3, 4, [5, 6]]

// 使用 flatMap() 方法展平数组并映射操作
const mappedAndFlattened = arr.flatMap(num => num * 2);
console.log(mappedAndFlattened); // [2, 4, 6, 8, 10, 12]

Object.fromEntries()

这个静态方法允许将键值对列表转换为对象。它接收一个键值对的可迭代对象(如数组)作为参数,并返回一个新的对象。

const entries = [['name', 'John'], ['age', 30], ['city', 'New York']];

// 将键值对列表转换为对象
const obj = Object.fromEntries(entries);
console.log(obj); // { name: 'John', age: 30, city: 'New York' }

String.prototype.trimStart()和String.prototype.trimEnd()

这两个方法用于去除字符串开头或结尾的空白字符。它们分别是trim()方法的单独扩展。
String.prototype.trimStart()是字符串原型对象上的一个方法,用于去除字符串开头的空白字符(空格、制表符、换行符等)。该方法返回一个新的字符串,不改变原始字符串本身。

例如,假设有一个字符串变量:

const str = "   Hello, World!   ";
我们可以使用trimStart()方法去除字符串开头的空白字符:

javascript
const trimmedStr = str.trimStart();
console.log(trimmedStr); 
// 输出: "Hello, World!   "

上述代码中,原始字符串开头的三个空格被删除了,得到新的字符串"Hello, World! "。

类似地,String.prototype.trimEnd()方法用于去除字符串结尾的空白字符。例如:

const str = "   Hello, World!   ";
const trimmedStr = str.trimEnd();
console.log(trimmedStr); 
// 输出: "   Hello, World!"

在这个例子中,最后面的三个空格被移除,返回新的字符串" Hello, World!"。

需要注意的是,这两个方法只会删除开头或结尾的空白字符,字符串中间的空白字符不会受到影响。如果需要同时删除开头和结尾的空白字符,可以直接使用原生的trim()方法:

const str = "   Hello, World!   ";
const trimmedStr = str.trim();
console.log(trimmedStr); 
// 输出: "Hello, World!"

String.prototype.trimStart()和String.prototype.trimEnd()是用于去除字符串开头和结尾的空白字符的方法。它们分别返回新的字符串,并保持原始字符串不变。如果需要同时删除开头和结尾的空白字符,可以使用trim()方法。

格式化数字

引入了新的Number.prototype.toFixed()方法,它允许指定小数点后的位数并将数字四舍五入为指定精度;而Intl.NumberFormat对象提供了更灵活和本地化的数字格式化。

动态导入

通过import()函数,可以在运行时动态地导入模块。这使得按需加载模块变得更加容易。

// 动态导入模块
import('./module.js')
  .then(module => {
    
    
    // 使用导入的模块
    module.doSomething();
  })
  .catch(error => {
    
    
    console.error('模块加载失败:', error);
  });

可选的catch绑定

现在可以在try-catch语句中省略catch块中的绑定,只使用catch {},而不会将错误绑定到变量。

try {
    
    
  // 执行可能抛出异常的代码
  throw new Error('发生了错误');
} catch {
    
    
  // 省略 catch 块中的绑定
  console.log('捕获到错误');
}

BigInt

引入了一种新的基本数据类型 BigInt,它可以表示任意精度的整数。使用后缀n来声明一个BigInt。

const bigNumber = BigInt("123456789012345678901234567890");

console.log(bigNumber); // 123456789012345678901234567890n
console.log(typeof bigNumber); // "bigint"

const added = bigNumber + 1n;
console.log(added); // 123456789012345678901234567891n

globalThis

引入了一个名为globalThis的全局属性,它始终指向全局对象,无论在什么环境下。

// 在浏览器控制台和 Node.js 中使用 globalThis
console.log(globalThis);

// 在浏览器全局作用域中声明变量
globalThis.myVariable = "Hello World";
console.log(myVariable); // "Hello World"

这些是ES10中的一些主要特性。它们提供了更方便、更强大的语言功能,使JavaScript开发人员能够更高效地编写代码。

猜你喜欢

转载自blog.csdn.net/weixin_48998573/article/details/131329645