从未定义中解构时避免错误 [英] Avoid an error when destructuring from undefined
本文介绍了从未定义中解构时避免错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我说我有这段代码:
const {x, y} = point;
Babel会将其转换为:
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"
.
那我该如何避免呢?
我想做类似的事情
const {x, y} = {} = point;
但这是语法错误.
我只能看到这是一个选择:
I can only see that this is an option:
const {x, y} = point || {};
哪个通天塔转移到:
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;
}
推荐答案
要处理ES6对象解构中的未定义错误,您可以执行以下操作
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
这篇关于从未定义中解构时避免错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文