Avoid an error when destructuring from undefined

后端 未结 2 2497
有刺的猬
有刺的猬 2021-02-20 18:34

Lets say I have this code:

const {x, y} = point;

Babel will turn this into:

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


        
2条回答
  •  孤独总比滥情好
    2021-02-20 19:29

    […] 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;
    }
    

提交回复
热议问题