新增操作符

可选链(Optional chaining)

  • 可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

  • ?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空nullish(null 或者undefined)的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

    let temp = obj.first;
    let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
    
    //可选链写法:
    let nestedProp = obj.first?.second
    //  ES2019的写法
    function doSomething(onContent, onError) {
      try {
        // ... do something with the data
      }
      catch (err) {
        if (onError) { // 校验onError是否真的存在
          onError(err.message);
        }
      }
    }
    
    // 使用可选链进行函数调用
    function doSomething(onContent, onError) {
      try {
       // ... do something with the data
      }
      catch (err) {
        onError?.(err.message); // 如果onError是undefined也不会有异常
      }
    }

空值合并运算符

空值合并操作符(**??**)是一个逻辑操作符,当左侧的操作数为 null或者 undefined时,返回其右侧操作数,否则返回左侧操作数。

与[逻辑或操作符||]不同,逻辑或操作符会在左侧操作数为[假值]时返回右侧操作数。

posted @ 2023-01-29 13:30  z_bky  阅读(30)  评论(0)    收藏  举报