使用Switch(true)模式

在做多条件时,我一般会尽量使用switch,但是判断的条件需要表达式时,就只能灰溜溜的去使用if-elseif-else了。今天看到switch true,这种模式非常简单,相信会是很好的体验。

基本介绍

大多数JavaScript开发人员都熟悉switch语句(mdn docs),但是对于那些刚接触该语言的人,让我们简要地介绍一下它。

switch语句使您可以将表达式与多种不同情况之一进行匹配:

const city = "London";

const getCountryByCity = () => {
  switch (city) {
    case "Edinburgh":
      return "Edinburgh is the capital city of Scotland";
    case "Madrid":
      return "Madrid is the capital city of Spain";
    case "London":
      return "London is the capital city of England";
    default:
      return "Cannot find which country this city is the capital of.";
  }
};

在这个例子中,表达式(城市变量)与switch语句中的每个case相匹配。如果案例与表达式的结果相匹配,案例将被执行--在这个例子中,它将返回一个字符串。

Switch (true)

switch true模式的基本原则是,你可以与表达式以及值相匹配。案例中的表达式将在匹配前被评估。如果你的案例中的表达式被评估为 "真",它将被匹配。

switch (true) {
  case 1 + 1 === 2:
  // This case evaluates to true so it will be executed
  default:
  // This will not be executed
}
为什么这很有用

这种模式可以在许多不同的情况下使用--通常用来替代复杂的if/else语句。

一个常见的情况是,如果你正在验证数据,并且有一组标准会导致验证失败,这种模式就会变得很方便。

const user = {
  firstName: "Seán",
  lastName: "Barry",
  email: "[email protected]",
  number: "00447123456789",
};

if (!user) {
  throw new Error("User must be defined.");
} else if (!user.firstName) {
  throw new Error("User's first name must be defined");
} else if (typeof user.firstName !== "string") {
  throw new Error("User's first name must be a string");
} else if (// ... lots more validation here)

return user;

这可以用switch true这样的方式重新编写。

const user = {
  firstName: "Seán",
  lastName: "Barry",
  email: "[email protected]",
  number: "00447123456789",
};

switch (true) {
  case !user:
    throw new Error("User must be defined.");
  case !user.firstName:
    throw new Error("User's first name must be defined");
  case typeof user.firstName !== "string":
    throw new Error("User's first name must be a string");
  default:
    return user;
}

在写if/else和switch true时,都可以抽象出验证标准,以提高可读性。

switch (true) {
  case !isDefined(user):
    throw new Error("User must be defined.");
  case !isString(user.firstName):
    throw new Error("User's first name must be a string");
  case !isValidEmail(user.email):
    throw new Error("User's email address must be a valid email address");
  case !isValidPhoneNumber(user.number):
    throw new Error("User's phone number must be a valid phone number");
  // any number of other validation cases here
  default:
    return user;
}
总结

在我看来,这种模式在检查多个条件时比大量的if/else块提供了更清晰的可读性。我相信这将会是一个很有争议的问题,但是了解这些模式总是很有用的,这样在适当的时候就可以使用它们。

你可能感兴趣的:(使用Switch(true)模式)