简体   繁体   English

如何简化多个if语句javascript?

[英]How to simplify multiple if statements javascript?

I have multiple conditions to check. 我有多个条件要检查。 I have to add icons based on the conditions, Then I need to change the background color based on some other set of conditions. 我必须根据条件添加图标,然后我需要根据其他一些条件来更改背景颜色。 I am using if statement. 我正在使用if语句。 This is my code. 这是我的代码。

JSON: JSON:

{
  "date": "2017-05-12",  
  "a": false,
  "b": true,
  "c": true,  
  "d": false,
  "status": "active"
}

Javascript: Javascript:

 if (date != -1) {
  //do something
  if (a) {
    //Add icon a
  }
  if (b) {
    //Add icon b
  }
  if (c) {
    //Add icon c
  }
  if (d) {
    //Add icon d
  }
}

if(status == "active"){
  //Background Green
}
else if (status == "onhold"){
  //Background Yellow
}
else if (status == "inactive"){
  //Background Red
}
else{
  //Backgeound Grey
}

How do I simplify it? 如何简化呢?

My idea is: 我的想法是:

var icons = {
    a: 'a.png',
    b: 'b.png',
    c: 'c.png',
    d: 'd.png',
}

if (date != -1) {
    Object.keys(icons).forEach(function(key) {
        if (data[key]) {
            //Add icon icons[key]
        }
    });
}

var statusColors = {
    active: 'Green',
    onhold: 'Yellow',
    inactive: 'Grey',
}

//Background statusColors[status]

The first half of you code looks fine. 您的代码的前半部分看起来不错。 For the second half of your code you should make use of a switch statement. 对于代码的后半部分,您应该使用switch语句。 These replace the if-else statements you are using and decide what to do when certain "cases" occur. 这些将替换您正在使用的if-else语句,并确定在发生某些“情况”时该怎么做。 For example: 例如:

switch(status) {
    case 'active':
        //background green
        break;
    case 'onhold':
        //background yellow
        break;
    case 'inactive':
        //background red
        break;
    default:
        //background grey
        break;
}

I think it is pretty good as it is. 我认为它确实不错。 Is is better to have understandable code than complex code that does exactly the same thing. 具有可理解的代码比做完全相同的事情的复杂代码更好。

You don't have to do 你不用做

if (a === true)

as it's equivalent to 因为它相当于

if ( a )

There is no way to "simplify" it, but you can try to use switch statement instead: 没有办法“简化”它,但是您可以尝试使用switch语句代替:

switch (status) {
  case 'active':
    // active
    break;
  case 'onhold':
    // onhold
    break;
  case 'inactive':
    // inactive
    break;
  default:
    console.log('default');
}

You can even "group" some conditions: 您甚至可以将某些条件“分组”:

switch (status) {
  case 'active':
  case 'onhold':
    // active AND onhold case
    break;
  case 'inactive':
    // inactive
    break;
  default:
    console.log('default');
}

More about switch statement -> https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch 有关switch语句的更多信息-> https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch

For Status variable you can use switch but for the first condition you have to use if-else statements I think. 对于Status变量,您可以使用switch,但是对于第一个条件,您必须使用if-else语句。

switch (status) {
        case "active":
            //Background Green
            break;
        case "onhold":
            //Background Yellow
            break;
        case "inactive":
            //Background Red
            break;
        default:
            //Backgeound Grey
    }

a?setIconA():b?setIconB:c?setIconC;d?setIconD

and

status == "active" ? setGreen() : status == "onhold": setYellow()

and so on. 等等。

Your question doesn't quite give the details of the actions in each case, but if they're very similar, and there's a match between the property name and whatever action you need to take, you can use loops. 您的问题并没有详细说明每种情况下的操作细节,但是如果它们非常相似,并且属性名称与您需要执行的任何操作之间都存在匹配,则可以使用循环。

['a','b','c','d'].forEach(function (k)
{
    if (objectFromJSON[k])
    {
       addIcon(k);
    }
});

For the second part, it's slightly more complex as you have status names that don't match the color. 第二部分,由于状态名称与颜色不匹配,因此稍微复杂一些。 You can either: 您可以:

  • define CSS classes with those status names, and use the status name to set the class: 使用这些状态名称定义CSS类,并使用状态名称来设置类:

    CSS: CSS:

     .status-active { background: green; } .status-onhold { background: yellow; } .status-inactive { background: red; } 

    JS: JS:

     theHTMLobject.classList.addClass('status-'+objectFromJSON.status); 
  • use an object's properties (or a Map) to convert the status into a color 使用对象的属性(或地图)将状态转换为颜色

Do you mean "simplify" or do you mean "shorten" - because the two are almost mutually exclusive (shorter code is often not simpler!) 您是说“简化”还是“缩短”-因为两者几乎是互斥的(较短的代码通常并不简单!)

Your code is clear, and understandable. 您的代码清晰易懂。 But it is a bit verbose, and can get much more complex as things grow. 但这有点冗长,并且随着事情的发展会变得更加复杂。 Sometimes it is better to shorten and the risk of making it a bit harder to understand. 有时,最好缩短并使它有点难以明白的风险。

You could consider things like a map between the status and the appropriate color 您可以考虑状态和适当颜色之间的映射等内容

var backgroundStatusMap = {
    "active":"green",
    "onhold": "yellow",
    "inactive": "red"
};

var backgroundColor = backgroundStatusMap[json.status];

Things like this can be added to easier if you as add new statuses - without having to trawl for the right place to put a new if.. condition. 如果您要添加新的状态,则可以更轻松地添加类似的内容-无需拖到正确的位置以放置新的if..条件。

Similarly, you could create a map for the booleans-to-icons 同样,您可以为booleans-to-icons创建一个映射

var iconMap = {
    "a":"icon_a.png",
    "b": "icon_b.png"
};

function getIcon(json, prop){
    if(json[prop])
      return iconMap[prop];
    return null;
}

var iconA = getIcon(json,"a");
var iconB = getIcon(json,"b");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM