Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...