优化三元表达式的几种方法

示例

loginType: this.SystemType === 'beijing' ? '2' : (this.SystemType === 'chengdu' || this.SystemType === 'chongqing') ? '1' : ''
  • 可以将这个三元表达式优化为更清晰和易读的形式,例如使用对象映射或 switch 语句。
  1. 使用对象映射
const loginTypeMap = {
  beijing: '2',
  chengdu: '1',
  chongqing: '1'
};

loginType: loginTypeMap[this.SystemType] || ''
  1. 使用 switch 语句
let loginType = '';
switch(this.SystemType) {
  case 'beijing':
    loginType = '2';
    break;
  case 'chengdu':
  case 'chongqing':
    loginType = '1';
    break;
  default:
    loginType = '';
}
  1. 保持三元但优化格式
loginType: this.SystemType === 'beijing' 
  ? '2' 
  : (this.SystemType === 'chengdu' || this.SystemType === 'chongqing') 
    ? '1' 
    : ''

你可能感兴趣的:(前端,javascript)