简体   繁体   English

Object 解构:在一行中分配 null 个值

[英]Object destructuring: Assign null values in one line

Assuming I have an object like this假设我有一个这样的 object

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

I would destructure it this way我会这样破坏它

const {a, b, c} = foo;

However, what, if the keys a , b and c do not exist?但是,如果键abc不存在怎么办?

foo = null;

This won't work then那这行不通

const {a, b, c} = foo;

I would have to do something like我将不得不做类似的事情

let a, b, c;

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

Is there a way to do this in one line?有没有办法在一行中做到这一点? Something like就像是

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

null is not an object. (evaluating '_ref2.a') null 不是 object。(评估“_ref2.a”)

When foo is not an object, you are going to have to give it an object so the destructuring can happen.当 foo 不是 object 时,您将不得不给它一个 object 以便解构发生。 So set it to an empty object using an 'or'.因此,使用“或”将其设置为空的 object。 Now if foo is defined it will use foo , if it is not defined it will use the default object.现在,如果定义了foo它将使用foo ,如果未定义它将使用默认值 object。

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

If you want default values, set them in the object.如果您想要默认值,请在 object 中设置它们。

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

If you want default values if the object does not provide them all, you can set values in the destructuring.如果 object 没有提供所有默认值,您可以在解构中设置值。

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

What about destructuring default parameters?解构默认参数怎么样? If foo could be undefined set = foo || {}如果 foo 可以是未定义的 set = foo || {} = foo || {} in destructuring to avoid exception = foo || {}在解构中避免异常

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

It will work like you might expect, the variables a b and c will be created with the value of undefined .它会像您预期的那样工作,变量a bc将使用undefined的值创建。 this is the fallback when also trying to access a property which doesn't exist on a certain object.当还尝试访问某个 object 上不存在的属性时,这是回退。

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM