代码之家  ›  专栏  ›  技术社区  ›  thebjorn

const{foo=20}=bar在javascript中是什么意思?[副本]

  •  0
  • thebjorn  · 技术社区  · 1 年前

    我找不到任何东西来搜索这个。根据我有限的测试,它看起来像

    const {foo = 20} = bar
    

    foo 将具有价值 bar.foo 如果它存在,否则它将具有值 20 即,它相当于:

    const foo = bar?.foo ?? 20
    

    我的理解正确吗?

    1 回复  |  直到 1 年前
        1
  •  4
  •   Error    1 年前

    不,这并不完全等同。

    区别:

    对于({foo=20}),如果bar.foo未定义,则使用默认值,但如果bar.fo为null,则不使用默认值。

    const {foo = 20} = bar
    

    使用(??)时,默认值用于null或undefined。

    const foo = bar?.foo ?? 20
    

    let bar = { foo: null };
    const { foo = 20 } = bar;
    console.log(foo); // null (not 20)
    
    bar = { foo: null };
    const fooVal = bar?.foo ?? 20;
    console.log(fooVal); // 20