JavaScript/ES6如何简写这段switch代码

爱许乐
  • 179
 numberTree: [

 10000000000000,

 18900,

 15700,

 12500,

 9300,

 7700,

 6100,

 4500,

 3700,

 2900,

 2100,

 1700,

 1300,

 900,

 700,

 500,

 300,

 200,

 100,

 0,

 ],
  switch (true) {

 case this.me.Total >= this.numberTree[0]:

 this.treenum = 19;

 break;

 case this.me.Total >= this.numberTree[1]:

 this.treenum = 18;

 break;

 case this.me.Total >= this.numberTree[2]:

 this.treenum = 17;

 break;

 case this.me.Total >= this.numberTree[3]:

 this.treenum = 16;

 break;

 case this.me.Total >= this.numberTree[4]:

 this.treenum = 15;

 break;

 case this.me.Total >= this.numberTree[5]:

 this.treenum = 14;

 break;

 case this.me.Total >= this.numberTree[6]:

 this.treenum = 13;

 break;

 case this.me.Total >= this.numberTree[7]:

 this.treenum = 12;

 break;

 case this.me.Total >= this.numberTree[8]:

 this.treenum = 11;

 break;

 case this.me.Total >= this.numberTree[9]:

 this.treenum = 10;

 break;

 case this.me.Total >= this.numberTree[10]:

 this.treenum = 9;

 break;

 case this.me.Total >= this.numberTree[11]:

 this.treenum = 8;

 break;

 case this.me.Total >= this.numberTree[12]:

 this.treenum = 7;

 break;

 case this.me.Total >= this.numberTree[13]:

 this.treenum = 6;

 break;

 case this.me.Total >= this.numberTree[14]:

 this.treenum = 5;

 break;

 case this.me.Total >= this.numberTree[15]:

 this.treenum = 4;

 break;
回复
阅读 2.2k
2 个回答
yzllee
  • 2.7k
✓ 已被采纳
const obj = {0:19,1:18,2:17,3:16};
for(const [key,value] of Object.entries(obj)) {
    if(this.me.Total >= this.numberTree[key]) {
        this.treenum = value;
        break;
    }
}

this.numberTree的下标+this.treenum固定等于19的话可以用循环去做

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏