代码之家  ›  专栏  ›  技术社区  ›  four-eyes

对象分解:在一行中分配空值

  •  -1
  • four-eyes  · 技术社区  · 4 年前

    假设我有一个这样的物体

    foo = {
        a: 1,
        b: 2,
        c: 3
    };
    

    我会这样分解它

    const {a, b, c} = foo;
    

    但是,如果钥匙 a , b c 不存在吗?

    foo = null;
    

    那就不行了

    常数{a,b,c}=foo;
    

    我得做点什么

    let a, b, c;
    
    if(foo) {
        a = foo.a;
        b = foo.b;
        c = foo.c;
    };
    

    有没有一种方法可以做到这一点?差不多

     const {a, b, c} = foo ? foo : null; // this is not working
    

    null不是一个对象。(评估“_ref2.a”)

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

    当foo不是一个对象时,必须给它一个对象,这样才能进行分解。因此,使用“or”将其设置为空对象。现在如果 foo 它将使用什么定义 ,如果未定义,将使用默认对象。

    const foo = undefined;
    const { a, b, c } = foo || {};
    console.log(a, b, c);

    如果需要默认值,请在对象中设置它们。

    const foo = undefined;
    const { a, b, c } = foo || {a : 'a', b: 'b', c: 'c' };
    console.log(a, b, c);

    如果需要默认值(如果对象没有提供所有值),则可以在分解中设置值。

    const foo = { a: 1};
    const { a = "a", b = "b", c = "c" } = foo || {};
    console.log(a, b, c);
        2
  •  0
  •   Ran Turner    4 年前

    它会像你预期的那样工作,变量 a b c 将以 undefined 。这是尝试访问某个对象上不存在的属性时的回退。

    const foo = {};
    console.log(foo.a); // undefined
    
    const {a, b, c} = foo;
    
    console.log(a); // undefined
    console.log(b); // undefined
    
    console.log(d); // Uncaught ReferenceError: d is not defined
        3
  •  0
  •   danylo    4 年前

    你可以指定 默认值 .

    例子:

    const { a = null, b = null, c = null } = foo;
    
        4
  •  0
  •   Bebiuz    4 年前

    如何分解默认参数? 如果foo可以是未定义集 = foo || {} 在解构中避免异常

    let foo = {};
    const {a = null, b = null, c = null} = foo;
    
    console.log('a:', a);
    console.log('b:', b);
    console.log('c:', c);