在javascript中评估代码三元运算符

时间:2018-04-18 09:46:05

标签: javascript

我有以下代码:

  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

1 个答案:

答案 0 :(得分:1)

您需要使用()包装三元运算符,以便将其视为字符串连接中的单个值:

let auth = {
  isAuthenticated: () => true,
  user: {
    email: 'test'
  }
};

console.log('Checking... ' +
  (auth.isAuthenticated() ?
    `User ${auth.user.email} is authenticated` :
    'User is not authenticated!')
);