如果定义了对象,我该如何对其进行解构?
const {url} = image; // only destructure if image is defined.
// don't want to nest the destructuring in if image condition
答案 0 :(得分:1)
如果说
仅在图像定义
时进行结构化
你的意思是它肯定是声明的,那么你可以这样做:
const {url} = image || {};
运行示例:
let image;
const {url} = image || {};
console.log('url is',url);

const image = {url: 'someUrl.com'};
const {url} = image || {};
console.log('url is', url);

答案 1 :(得分:0)
目标必须至少声明:
let image;
const { url } = image ? image : {}; // undefined
console.log(url)
let image = { url: '/some/path' };
const { url } = image ? image : {};
console.log(url)