⑨ ES11 新特性初探

1 全局模式捕获:String.prototype.matchAll()

const str = `
  <html>
    <body>
      <div>这是第一个div</div>
      <p>这是p</p>
      <div>这是第二个div</div>
      <span>这是span</span>
    </body>
  </html>
`

1.1 String.prototype.exec() + /g

  • 如果正则表达式有 /g 标志,那么多次调用 .exec() 就会得到所有匹配的结果
// 找出所有的div元素的内容
function selectDiv(regExp, str) {
  let matches = []
  while(true) {
    const match = regExp.exec(str)
    if(match == null) {
      break
    }
    matches.push(match[1])
  }
  return matches
}
const regExp = /<div>(.*)<\/div>/g // 捕获组
const res = selectDiv(regExp, str)
console.log(res); // ['这是第一个div', '这是第二个div']

1.2 match

const regExp = /<div>(.*)<\/div>/g // 捕获组
console.log(str.match(regExp)); // ['<div>这是第一个div</div>', '<div>这是第二个div</div>']

1.3 replace

const regExp = /<div>(.*)<\/div>/g // 捕获组
function selectDiv(regExp, str) {
  let matches = []
  str.replace(regExp, (all, first) => {
    console.log(all, first);
    matches.push(first)
  })
  return matches
}
const res = selectDiv(regExp, str)
console.log(res);

2 动态导入:Dynamic import()

  • 案例:页面上有一个按钮,点击按钮才去加载 ajax 模块
const oBtn = document.querySelector('#btn')
oBtn.addEventListener('click', () => {
  import('./ajax').then(mod => {
    mod.default('static/a.json', res => {
      console.log(res);
    })
  })
})

3 新的原始数据类型:BigInt

const max = 2 ** 53
console.log(max); // es7 幂运算符
console.log(Number.MAX_SAFE_INTEGER); // 最大值-1
console.log(max === max + 1); // true
  1. 定义 BigInt 方式①:...n
const bigInt = 9007199254740993n
console.log(bigInt); //9007199254740993n
console.log(typeof bigInt); //bigint

console.log(1n == 1); // true
console.log(1n === 1); // false
  1. 定义 BigInt 方式②:BigInt(...n)
const bigInt2 = BigInt(9007199254740993n)
console.log(bigInt2);
const num = bigInt + bigInt2
console.log(num); // 18014398509481986n
console.log(num.toString()); // 18014398509481986

4 Promise扩展:Promise.allSettled()

4.1 Promise.all()

Promise.all([
  Promise.resolve({
    code: 200,
    data: [1, 2, 3]
  }),
  Promise.reject({
    code: 500,
    data: []
  }),
  Promise.resolve({
    code: 200,
    data: [7, 8, 9]
  })
]).then(res => {
  console.log(res);
  console.log('成功');
}).catch(err => {
  console.log(err);
  console.log('失败');
})

err: { code: 500, data: [] }

4.2 Promise.allSettled()

  • 如果并发任务中,无论一个任务正常或者异常,都会返回对应的状态
Promise.allSettled([
  Promise.resolve({
    code: 200,
    data: [1, 2, 3]
  }),
  Promise.reject({
    code: 500,
    data: []
  }),
  Promise.resolve({
    code: 200,
    data: [7, 8, 9]
  })
]).then(res => {
  console.log(res);
  console.log('成功');
  const data = res.filter(item => item.status === 'fulfilled')
  console.log(data);
}).catch(err => {
  console.log(err);
  console.log('失败');
})

res:
[{status: 'fulfilled', value: { code: 200, data: [1, 2, 3] }}, 
 {status: 'rejected', reason: { code: 500, data: [] }},
 {status: 'fulfilled', value: { code: 200, data: [7, 8, 9] }}]

data:
[{status: 'fulfilled', value: { code: 200, data: [1, 2, 3] }}, 
 {status: 'fulfilled', value: { code: 200, data: [7, 8, 9] }}]

5 全局对象:globalThis

  • Javascript 在不同的环境获取全局对象有不通的方式:

    1. node: global

    2. web: window self

      • self:打开任何一个网页,浏览器会首先创建一个窗口,这个窗口就是一个 window 对象,也是 js 运行所依附的全局环境对象和全局作用域对象。
self.setTimeout(() => {
  console.log('es2020');
}, 1000);
  • 提供了一个标准的方式去获取不同环境下的全局对象
const getGlobal = () => {
  if(typeof self !== 'undefined') {
    return self
  }
  if(typeof window !== 'undefined') {
    return window
  }
  if(typeof global !== 'undefined') {
    return global
  }
  throw new Error('无法找到全局对象')
}
const global = getGlobal()
console.log(global);
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
console.log(globalThis);
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}

6 可选链:Optional chaining

  • 可选链中的 ? 表示如果问号左边表达式有值, 就会继续查询问号后面的字段

用可选链可以大量简化类似繁琐的前置校验操作,而且更安全

const user = {
  address: {
    street: 'xx街道',
    getNum() {
      return '80号'
    }
  }
}
const street = user?.address?.street
console.log(street);
const num = user?.address?.getNum?.()
console.log(num);

7 空值合并运算符:Nullish coalescing Operator

  • 使用空值合并操作符为常量提供默认值,保证常量不为 null 或者 undefined

当左侧操作数为 nullundefined 时,返回右侧操作数,否则返回左侧操作数

const b = false
// const a = b || 5
const a = b ?? 5
console.log(a);
posted on 2022-05-18 17:46  pleaseAnswer  阅读(22)  评论(0编辑  收藏  举报