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;
    

      

  • 相关阅读:
    The FLARE On Challenge
    CVE-2013-2551漏洞成因与利用分析(ISCC2014 PWN6)
    CVE-2014-0322漏洞成因与利用分析
    CVE-2013-3897漏洞成因与利用分析
    译:《深入解析WINDOWS VISTA APC》——PART 1
    MemoryInjector 无痕注入
    一个APC引起的折腾 之题外记
    一个APC引起的折腾
    2020
    javascriptcore调试笔记
  • 原文地址:https://www.cnblogs.com/jason-hhc/p/13921900.html
Copyright © 2011-2022 走看看