How to make this if statement shorter?

后端 未结 6 491
执念已碎
执念已碎 2021-01-28 04:57

Can I make this statement shorter?

if(abc==\'value1\' || abc==\'value2\' || abc==\'value3\') {//do something}

to make it look similar to this:<

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-28 05:38

    You have a couple options:

    1. Leave it as it is;
    2. Use an associative array/object;
    3. Use a switch statement.

    The second form is not valid Javascript syntax.

    (2) is something like:

    var abcOptions = {
      "value1" : true,
      "value2" : true,
      "value3" : true
    };
    if (abcOptions[abc]) {
      ...
    }
    

    (3) is:

    switch (abc) {
      case "value1":
        ...
        break;
      case "value2":
        ...
        break;
      case "value3":
        ...
        break;
    }
    

    Personally I'm not a huge fan of this from a readability point of view but it's a reasonable approach with a large number of values.

    I don't necessarily recommend this but it might be an option in certain circumstances. If you're only dealing with three values stick with:

    if (abc == "value1" || abc == "value2" || abc == "value3") {
      ...
    }
    

    as it's much more readable.

提交回复
热议问题