如何用对象文字替换开关

How to replace switch with Object literals

当我重写我的旧代码时,我遇到了一个问题,我不知道如何优化这段代码,过去我使用 switch,但现在我知道了对象文字,我的代码:

switch(true) {
 case data.rep <= -30:
    reputation_text = this.language.pf.reputation.satan;
    break;
 case data.rep >= -10 && data.rep <= -5:
    reputation_text = this.language.pf.reputation.devil;
    break;
 //other....

 case data.rep >= 30:
 reputation_text = this.language.pf.reputation.angel;
 break;
}

如何用对象字面量替换他?

您可以将案例写成对象字面量并对其进行迭代:

const { reputations } = this.language.pf;

type MapEntry = { min: number; max: number; value: keyof typeof reputations };

const mapTable: MapEntry[] = [
  { min: Number.MIN_VALUE, max: -30, 
    value: "satan" },
  { min: -10, max: -5, 
    value: "devil" },
  // ...
  { min: 30, max: Number.MAX_VALUE, 
    value: "angel" },
];

for (const entry of mapTable) {
  if (Data.rep >= entry.min && Data.rep <= entry.max) {
    reputation_text = reputations[entry.value];
    break;
  }
}