H5W3
当前位置:H5W3 > 其他技术问题 > 正文

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

 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;

回答

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

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;
    }
}

未经允许不得转载:H5W3 » JavaScript/ES6如何简写这段switch代码

赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址