美文网首页js css html
ES6中(?.、??)运算符的使用

ES6中(?.、??)运算符的使用

作者: NemoExpress | 来源:发表于2022-05-18 15:09 被阅读0次

    可选链操作符( ?. )

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

    当尝试访问可能不存在的对象属性时,可选链操作符将会使表达式更短、更简明。在探索一个对象的内容时,如果不能确定哪些属性必定存在,可选链操作符也是很有帮助的。

    a?.b
    // 等同于
    a == null ? undefined : a.b
    a?.[x]
    // 等同于
    a == null ? undefined : a[x]
    a?.b()
    // 等同于
    a == null ? undefined : a.b()
    a?.()
    // 等同于
    a == null ? undefined : a()
    
    const obj = {name: 'xu'}
    console.log(obj?.data?.list)  // undefined
    console.log(obj?.name?.length)  //2
    console.log(obj?.age) // undefined
    
    const people= {
      name: 'xu',
      cat: {
        name: 'Bob'
      }
    };
    const dogName = adventurer.dog?.name;
    console.log(dogName); // undefined
    console.log(people.someNonExistentMethod?.()); // undefined
    console.log(people.someNonExistentMethod()); //报错
    

    空值合并操作符(??

    空值合并操作符(??)是一个逻辑操作符,仅仅当左侧的操作数为 null 或者 undefined 时,才返回其右侧操作数,否则返回左侧操作数。 空值合并操作符(??)与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。

    //   ||运算符
        var a = obj || {}
    等价于
        var a;
        if(obj === 0 || obj === "" || obj === false || obj === null || obj === undefined){
        a = {}
        } else {
        a = obj;
        }
    
    //  ??运算符
        var a = obj ?? {}
    等价于
        var a;
        if( obj === null || obj === undefined){
        a = {}
         } else {
        a = obj;
        }
    
    var ibo = {}
    console.log(ibo?.a ?? 111) //  111
    var ibo = {a:{b:1}}
    console.log(ibo?.a?.b ?? 111) //1
    
    console.log(1??'2') //  1
    console.log(null ?? "xx") // xx
    console.log(undefined ?? "xx") //  xx
    console.log( ' '?? "xx")  //  空值
    

    相关文章

      网友评论

        本文标题:ES6中(?.、??)运算符的使用

        本文链接:https://www.haomeiwen.com/subject/afdaurtx.html