zoukankan      html  css  js  c++  java
  • ES6 语句判断简写

    链判断运算符

    编程实务中,如果读取对象内部的某个属性,往往需要判断一下该对象是否存在。比如,要读取message.body.user.firstName,安全的写法是写成下面这样。

    // 错误的写法
    const  firstName = message.body.user.firstName;
    
    // 正确的写法
    const firstName = (message
      && message.body
      && message.body.user
      && message.body.user.firstName) || 'default';
    

      这样的层层判断非常麻烦,因此 ES2020 引入了“链判断运算符”(optional chaining operator)?.,简化上面的写法。

    const firstName = message?.body?.user?.firstName || 'default';
    const fooValue = myForm.querySelector('input[name=foo]')?.value
    

      

    Null 判断运算符

    读取对象属性的时候,如果某个属性的值是nullundefined,有时候需要为它们指定默认值。常见做法是通过||运算符指定默认值。

    const headerText = response.settings.headerText || 'Hello, world!';
    const animationDuration = response.settings.animationDuration || 300;
    const showSplashScreen = response.settings.showSplashScreen || true;
    

      上面的三行代码都通过||运算符指定默认值,但是这样写是错的。开发者的原意是,只要属性的值为nullundefined,默认值就会生效,但是属性的值如果为空字符串或false0,默认值也会生效。

    为了避免这种情况,ES2020 引入了一个新的 Null 判断运算符??。它的行为类似||,但是只有运算符左侧的值为nullundefined时,才会返回右侧的值。

    const headerText = response.settings.headerText ?? 'Hello, world!';
    const animationDuration = response.settings.animationDuration ?? 300;
    const showSplashScreen = response.settings.showSplashScreen ?? true;
    

      

  • 相关阅读:
    uboot中打开 debug调试信息的方法
    如何知道外围器件的器件地址PHY_ADDR
    附录:ARM 手册 词汇表
    ARM协处理器CP15寄存器详解
    浅析ARM协处理器CP15寄存器有关指令:MCRMRC
    uboot-的start.S详细注解及分析
    Shell中的算数运算
    Linux下的expect
    Linux 常用工具sysstat之iostat
    Linux的top命令
  • 原文地址:https://www.cnblogs.com/jason-hhc/p/13921900.html
Copyright © 2011-2022 走看看