首页 > 技术文章 > 应该掌握的 JS 小技巧

m7777 2022-04-28 09:40 原文

1. 用??代替||,用于判断运算符左侧的值为nullundefined时,才返回右侧的值

??运算符是 ES2020 引入,也被称为null判断运算符( Nullish coalescing operator)

它的行为类似||,但是更严

||运算符是左边是空字符串或false0falsy值,都会返回后侧的值。而??必须运算符左侧的值为nullundefined时,才会返回右侧的值。因此0||1的结果为1,0??1的结果为0

例如

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false
复制代码

浏览器支持情况

image.png

2. 使用?.简化&&和三元运算符

?.也是ES2020 引入,有人称为链判断运算符(optional chaining operator)

?.直接在链式调用的时候判断,判断左侧的对象是否为nullundefined,如果是的,就不再往下运算,返回undefined,如果不是,则返回右侧的值

例如

var street = user.address && user.address.street;

var fooInput = myForm.querySelector('input[name=foo]')
var fooValue = fooInput ? fooInput.value : undefined

// 简化
var street = user.address?.street
var fooValue = myForm.querySelector('input[name=foo]')?.value
复制代码

注: 常见写法

  • obj?.prop  对象属性
  • obj?.[expr]  对象属性
  • func?.(...args)  函数或对象方法的调用

浏览器支持情况

image.png

3. 使用动态导入import()实现按需加载(优化静态import)

我们可以使用 import 语句初始化的加载依赖项

import defaultExport from "module-name";
import * as name from "module-name";
//...
复制代码

但是静态引入的import 语句需要依赖于 type="module"script标签,而且有的时候我们希望可以根据条件来按需加载模块,比如以下场景:

  • 当静态导入的模块很明显的降低了代码的加载速度且被使用的可能性很低,或者并不需要马上使用它
  • 当静态导入的模块很明显的占用了大量系统内存且被使用的可能性很低
  • 当被导入的模块,在加载时并不存在,需要异步获取
  • 当被导入的模块有副作用,这些副作用只有在触发了某些条件才被需要时

这个时候我们就可以使用动态引入import(),它跟函数一样可以用于各种地方,返回的是一个 promise

基本使用如下两种形式

//形式 1
import('/modules/my-module.js')
  .then((module) => {
    // Do something with the module.
  });
  
 //形式2
let module = await import('/modules/my-module.js');
复制代码

浏览器支持情况

image.png

4. 使用顶层 await(top-level await)简化 async 函数

其实上面的代码就有用到

let module = await import('/modules/my-module.js');
复制代码

顶层 await 允许开发者在 async 函数外部使用 await 字段

因此

//以前
(async function () {
  await Promise.resolve(console.log('

推荐阅读