我有以下代码:
console.log('Checking... ' +
auth.isAuthenticated() ?
`User ${auth.user.email} is authenticated` :
'User is not authenticated!'
);
如果isAuthenticated
返回false,则auth.user未定义。
因此,尝试在auth.user.email
时打印isAuthenticated==false
会导致错误。
但就我而言,我只想在auth.user.email
时打印auth.isAuthenticated==true
,但我仍然会收到此错误:
TypeError: Cannot read property 'email' of undefined
答案 0 :(得分:1)
您需要使用()
包装三元运算符,以便将其视为字符串连接中的单个值:
let auth = {
isAuthenticated: () => true,
user: {
email: 'test'
}
};
console.log('Checking... ' +
(auth.isAuthenticated() ?
`User ${auth.user.email} is authenticated` :
'User is not authenticated!')
);