美文网首页
js 一些运算符

js 一些运算符

作者: 八妹sss | 来源:发表于2022-06-15 09:57 被阅读0次
    ?. 运算符

    作用:在一个变量可能为null、或者undefined的时候,恰巧我又需要访问这个变量的一个属性,则用?.,有值则返回对应的值,否则返回undefined
    例:

    image.png
    const obj = {hh: 'xxx'}
    let res = obj?.data?.list
    console.log(res)  // undefined
    console.log(obj?.hh?.length)  //3
    console.log(obj?.hh) // xxx
    
    ?? 运算符

    作用:当??左侧的值是null或undefined时,取??右侧的值
    例:


    image.png
    image.png
    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")  //  空值
    
    ??= 运算符

    作用:当??左侧的值是null或undefined时,取??右侧变量的值赋值给左侧变量
    例:

    let b = '你好';
    let a = 0
    let c = null;
    let d = ’123‘
    b ??= a;  // b = “你好”
    c ??= d  // c = '123'
    

    测验题:

    let a;
    let b = "不知名前端"
    let c = null;
    let d = 0;
    let e;
    
    e ??= a?.b ?? c ?? d?.a ?? b;
    console.log(e)
    

    相关文章

      网友评论

          本文标题:js 一些运算符

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