• 可选链操作符(?.) 空值合并操作符(??)


    一、 ?.

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

    let nestedProp = obj.first && obj.first.second;
    // 等价于
    let nestedProp = obj.first?.second;

    js会在尝试访问obj.first.second之前隐式的检查并确定obj.first既不是null也不是undefined。如果obj.firstnull或者undefined,表达式将会短路计算直接返回undefined

    二、??

    空值合并操作符,可以在使用可选链时设置一个默认值

    let customer = {
      name: "Carl",
      details: { age: 82 }
    };
    let customerCity = customer?.city ?? "暗之城";
    console.log(customerCity); // “暗之城”
     
    const nullValue = null;
    const emptyText = ""; // 空字符串,是一个假值,Boolean("") === false
    const someNumber = 42;
     
    const valA = nullValue ?? "valA 的默认值";
    const valB = emptyText ?? "valB 的默认值";
    const valC = someNumber ?? 0;
     
    console.log(valA); // "valA 的默认值"
    console.log(valB); // ""(空字符串虽然是假值,但不是 null 或者 undefined)
    console.log(valC); // 42

    三、语法

    obj?.prop
    obj?.[expr]
    arr?.[index]
    func?.(args)

    四、为变量赋默认值

    以前,如果想为一个变量赋默认值,通常的做法是使用逻辑或操作符(||

    let count = 0;
    let text = "";
     
    let qty = count || 42;
    let message = text || "hi!";
    console.log(qty);     // 42,而不是 0
    console.log(message); // "hi!",而不是 ""

    空值合并操作符可以避免这种陷阱,其只在第一个操作数为null 或 undefined 时(而不是其它假值)返回第二个操作数:

    let myText = ''; // An empty string (which is also a falsy value)
     
    let notFalsyText = myText || 'Hello world';
    console.log(notFalsyText); // Hello world
     
    let preservingFalsy = myText ?? 'Hi neighborhood';
    console.log(preservingFalsy); // '' (as myText is neither undefined nor null)

    转自:https://blog.csdn.net/czx3387170/article/details/121693204

  • 相关阅读:
    使用MongoDB ruby驱动进行简单连接/CRUD/运行命令
    DBMS-SQL:聚集函数、嵌套子查询、数据库修改
    国内无法使用gem install解决办法
    AI-Local search&Nodeterministic Problems&Partial observations&Online search
    DBMS-关系模型
    DBMS-基本概念
    ros安装过程中部分包“hash校验和不符”报错解决办法
    AI: Chapter 3-Solving problems by searching
    Map数据结构
    Set和WeakSet数据结构
  • 原文地址:https://www.cnblogs.com/strongerPian/p/16473914.html
Copyright © 2020-2023  润新知