小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
本文同时参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金
1. String.prototype.matchAll
1.1 简介
ES2020新增String.prototype.matchAll, 用于一次性取出所有匹配。该方法会返回一个装有所有匹配结果、捕获组的遍历器。相对于数组,遍历器处理一个较大的数组将会比较节约资源。该方法返回的迭代器不可重用,结果消耗完需要再次调用此方法,以获得一个新的迭代器。迭代器可以结合for...of 或 Array.from来方便的处理。
在matchAll诞生前,我们一直通过regexp.exec() 来获取所有匹配项的信息。
const reg = RegExp('foo[a-z]*', g)
const string = 'table football, foosball'
let match
while((match = reg.exec(string)) !== null) {
console.log(reg)
}
// ["football", index: 6, input: "table football, foosball", groups: undefined]
// ["foosball", index: 16, input: "table football, foosball", groups: undefined]
1.2 matchAll的基本使用
const reg = RegExp('foo[a-z]*', 'g')
const string = 'table football, foosball'
const arr = Array.from(string.matchAll(reg), (res) => res[0]) // ["football", "foosball"]
2. Import.meta
2.1 简介
开发者使用一个模块时, 有时候想知道模块本身的信息,例如模块的路径等。ES2020为import命令添加了一个元属性 import.meta, 返回当前模块的元信息。
例如,如果想要知道当前模块的路径,可以通过import.meta.url来访问到。import.meta只能在模块内部使用。
import.meta.url
<script type="module" src='./index.js'></script>
// 在index.js中
import vue from 'vue'
console.log(import.meta) // url
import.meta.scriptElement
<script type="module" src="index.js" data-people="alice"></script>
// index.js 内执行下面的代码
import.meta.scriptElement.dataset.people // "alice"
3. GlobalThis 对象
3.1 简介
JavaScript 是我们最强大的武器,它可以用于浏览器、服务端和原生开发等。而每个不同的环境都有其自己的全局对象。
例如:
- 浏览器中我们可以通过
window、self、frames访问全局对象。 Node.js中可以使用global访问顶层对象。Web Worker中则是通过self
不同的环境有不同的全局对象, 这使得跨端开发变得更困难。而ES2020的 globalThis 特性则使得不同的环境都能通过统一的方式拿到顶层对象。
3.2 基本使用
if (typeof globalThis.setImmediate !== 'function') {
console.log('当前环境中不存在setImmediate方法~')
}
4. BigInt
4.1 简介
在ES11前,JavaScript将数字存储为64位浮点数,导致大于等于2的1024次方的数会返回 Infinity。
ES11为解决这种问题引入了一种新的数据类型 BigInt 大整数类型,它用来存储任意位数的整数。
4.2 基本使用
const a = 99999n
const b = BigInt(99999)
typeof a // 'bigint'
typeof b // 'bigint'
// 类型转换
// 可用 Boolean()、Number()和 String()这三个方法,将 BigInt 可以转为布尔值、数值和字符串类型。
Boolean(0n) // false
Boolean(1n) // true
Number(1n) // 1
String(1n) // "1"
!0n // true
!1n // false
// 运算 除了>>>(无符号右移位)外,bigInt支持+、-、*、%等大部分运算符
const res = a + b // 199998n
const res2 = 5n / 2n // 除法运算会向下取整 ,得2n
const res3 = 3n + 3 // bigInt不能和普通数字混合计算
点赞支持、手留余香、与有荣焉,动动你发财的小手哟,感谢各位大佬能留下您的足迹。
往期精彩推荐
Vue 虚拟 DOM 搞不懂?这篇文章帮你彻底搞定虚拟 DOM
Git 相关推荐
面试相关推荐
更多精彩详见:个人主页