例如:
data = {info: {name: john}}
我怎样才能确定:
const name = data.info.name
name
存在,我不会得到:Can't read value name of undefined
现在我正在做:
let name
if(!!data && data.info && data.info.name){
name = data.info.name
}
但它似乎很乱,想知道是否有更好的方式
答案 0 :(得分:3)
您不需要if
语句,您可以直接指定表达式:
const data = {info: {name: 'john'}};
const name = data && data.info && data.info.name
console.log(name);
const data2 = {};
const name2 = data2 && data2.info && data2.info.name;
console.log(name2);

您可以使用destructuring assignment默认值:
const data = {info: {name: 'john'}};
const { info: { name } = {}} = data || {};
console.log(name);
const data2 = undefined;
const { info: { name2 } = {}} = data || {};
console.log(name2);

还有TC39 stage 1 proposal - optional chaining,您可以使用babel plugin:
const data = {info: {name: 'john'}};
// if any part of chain is undefined, name will be undefined
const name = data?.info?.name;