ES2020可选链操作符(?.)

?. 的概念:

  允许读取位于连接对象深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 操作符,不同之处在于,在引用为空的情况下不会引起错误,该表达式短路返回值是undefined。与函数一起使用时,如果给定的函数不存在,则返回undefined。

以上是MDN的解释:自己理解就是如果 ?. 左侧的值转布尔值为false,则返回undefined,如果为true,则继续往右执行。下面的案例给与理解这一点

 

比如从后台接口访问详细的用户信息:

    const response = {
      data: {
        user: {
          name: "小王",
        },
      },
    };

为了在取出name的过程中程序不报错,

1、使用嵌套的三元表达式

    const userName = response ? response.data ? response.data.user ? response.data.user.name : null : null : null;

2、使用 && 连接

    const userName = response && response.data && response.data.user && response.data.user.name;

3、使用 ?. 

    const userName = response?.data?.user?.name;

最简洁的是第三种方式,只需要保证 !!response===true,这段代码就不会报错,取不到最后的name就会返回undefined

 

 

复制代码
    const user = {
      name: "小王同志",
      age: 18,
      homeaddress: {
        country: "中国",
      },
      hobbies: [{ name: "敲代码" }, { name: "洗碗" }],
      getFirstName: function (data) {
        return data;
      },
    };
    console.log(user.homeaddress.country) // 中国
    // console.log(user.homeaddress1.country) // Uncaught TypeError: Cannot read property 'country' of undefined
    console.log(user.homeaddress1?.country) // undefined

    console.log(user.getFirstName('123')) // '123'
    console.log(user.getFirstName?.(123)) // 123
    console.log(user.getFirstName1?.(123)) // undefined

    console.log(user.hobbies[0].name) // 敲代码
    // console.log(user.hobbies[3].name) // Uncaught TypeError: Cannot read property 'name' of undefined
    console.log(user.hobbies[3]?.name) // undefined
    console.log(user.hobbies1?.[3]?.name) // undefined
复制代码

 

 

和 ?? 搭配使用:

    const obj = {
      name: "小明",
    };
    const result = obj?.name1 ?? "大明";
    console.log(result); // 大明

 

posted @   吴小明-  阅读(390)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示