Avoid an error when destructuring from undefined

不问归期 提交于 2020-01-02 02:01:09

问题


Lets say I have this code:

const {x, y} = point;

Babel will turn this into:

var _point = point,
    x = _point.x,
    y = _point.y;

Which is fine, but what if point is undefined? Now I get an error:

"Cannot read property 'x' of undefined".

So how do I avoid this?

I want to do something like

const {x, y} = {} = point;

but that's a syntax error.

I can only see that this is an option:

const {x, y} = point || {};

Which babel transpiles to:

var _ref = point || {},
    x = _ref.x,
    y = _ref.y;

Here we're creating an object just to avoid an undefined error. This seems wasteful.

Is there some syntax I'm missing that would avoid this? Something that would transpile to something like this:

var x, y;
if (typeof point !== 'undefined') {
    x = point.x;
    y = point.y;
}

回答1:


To handle undefined error in ES6 object destructuring, you can do something like following

const {x, y} = {...point};
console.log(x)      // undefined                  
console.log(y)      // undefined                  



回答2:


[…] what if point is undefined? Now I get an error: "Cannot read property 'x' of undefined"

So how do I avoid this?

If you want to write clear code, you can explicitly check that condition:

let { x, y };
if (typeof point === 'undefined') {
    x = y = undefined;
} else {
    { x, y } = point;
}


来源:https://stackoverflow.com/questions/44886621/avoid-an-error-when-destructuring-from-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!