HOWTO · JavaScript

在 Javascript 中切换多个案例

本教程详细介绍了如何从其类名中获取元素。

本页内容

Switch case 的性能比 if-else 阶梯高得多。它们有一个从变量值的直接映射,在 switch(variable) 块中,到它们对应的值,在 case: value 块中。我们熟悉单值映射的常见 switch-case 用法,但它可以支持多种情况吗?让我们看看在 javascript 中,我们可以在 switch-case 块中有多个 case 的几种方法。

在 Javascript 中使用 Fall Through 模型使用多个案例的切换

Fall through 模型是在 JavaScript 中使用多个 case 块支持 switch 的第一步。在这里,我们通过多种情况捕获切换变量的多个值。我们将 break 关键字应用于一组有效的情况。例如,如果我们想根据过去的月份记录一年的季度名称,我们将根据季度对月份指数进行分组。参考以下代码。

window.onload =
    function() {
  findQuarter('2021-08-08');
  findQuarter('2021-05-12');
  findQuarter('2021-02-28');
  findQuarter('2021-11-30');
}

function findQuarter(dateString) {
  var monthIndex = new Date(dateString).getMonth();
  switch (monthIndex) {
    case 0:
    case 1:
    case 2:
      console.log('First Quarter');
      break;
    case 3:
    case 4:
    case 5:
      console.log('Second Quarter');
      break;
    case 6:
    case 7:
    case 8:
      console.log('Third Quarter');
      break;
    case 9:
    case 10:
    case 11:
      console.log('Fourth Quarter');
      break;
  }
}

输出:

Third Quarter
Second Quarter
First Quarter
Fourth Quarter

findQuarter() 函数接受格式为 yyyy-mm-dd 的日期字符串。然后它通过首先将其转换为 javascript 日期对象,然后从日期对象中获取月份索引,从 dateString 参数中提取月份索引。getMonth() 是一个 javascript 函数,它应用于 Date 对象并返回从 0 开始的月份索引。我们在这里使用多个案例,一个堆叠在另一个下面以捕获输出的多个值。

例如,对于从 1 月到 3 月的月份,根据 getMonth() 函数返回的输出,相应的月份索引的范围是 0 到 2。我们在没有 break 关键字的情况下将所有情况从 0 堆叠到 2。因此,他们会绊倒并在遇到 break 时打破 switch-case,该 break 恰好在 case 2: 行中,它记录了值 First Quarter。这组代码看起来很笨重。我们可以按如下方式重写相同的内容以减少行数。

window.onload =
    function() {
  findQuarter('2021-08-08');
  findQuarter('2021-05-12');
  findQuarter('2021-02-28');
  findQuarter('2021-11-30');
}

function findQuarter(dateString) {
  var monthIndex = new Date(dateString).getMonth();
  switch (monthIndex) {
    case 0:
    case 1:
    case 2:
      console.log('First Quarter');
      break;
    case 3:
    case 4:
    case 5:
      console.log('Second Quarter');
      break;
    case 6:
    case 7:
    case 8:
      console.log('Third Quarter');
      break;
    case 9:
    case 10:
    case 11:
      console.log('Fourth Quarter');
      break;
  }
}

输出:

Third Quarter
Second Quarter
First Quarter
Fourth Quarter

请注意,这里的输出保持不变。这只是编写 Fall through switch-case 模型的另一种方式。它使代码现在看起来更干净并节省空间。

使用 JavaScript 中的数学表达式处理 Switch 中的多个案例

我们正在按照前面部分中提到的示例处理一个月的数值。我们可以在 case 块中使用 expressions 吗?绝对是的!在解释功能之前,让我们参考以下代码。

window.onload =
    function() {
  findQuarter('2021-08-08');
  findQuarter('2021-05-12');
  findQuarter('2021-02-28');
  findQuarter('2021-11-30');
  findQuarter('2021-2-30');
}

function findQuarter(dateString) {
  var monthIndex = new Date(dateString).getMonth();
  switch (monthIndex) {
        case ( (monthIndex < 2) ? monthIndex : -1 ):
            console.log('First Quarter');
          break;
        case ( ((monthIndex > 2) && (monthIndex < 5)) ?  monthIndex : -1):
            console.log('Second Quarter');
          break;
        case ( ((monthIndex > 5) && (monthIndex < 8)) ?  monthIndex : -1):
            console.log('Third Quarter');
          break;
        case ( ((monthIndex > 8) && (monthIndex < 11)) ?  monthIndex : -1):
            console.log('Fourth Quarter');
          break;
        default:
          console.log('Invalid date');
          break;
  }
}

输出:

Third Quarter
Second Quarter
First Quarter
Fourth Quarter

如果我们在 switch case 中使用表达式,它们必须返回一个数字值,否则为 -1。在上面的代码片段中,我们在 case 块中添加了数字表达式而不是它们的实际值。这些表达式计算月份的相应季度并记录季度名称。在这里,我们在 switch case 中包含了 default 子句来处理 Invalid date。如果 date 中的 month 有效(在 1 到 12 的范围内),JavaScript 中的 getMonth() 方法返回一个值(介于 0 和 11 之间),否则它将返回 NaN。default 块将捕获此类无效日期场景。

使用 Javascript 中的字符串表达式处理 Switch 中的多个 case

我们还可以在 case 块中使用字符串表达式。这些表达式在运行时计算,执行 case 子句。对于我们的月份示例,让我们尝试切换月份名称。为此,我们将在日期对象上应用 toLocaleDateString() 函数。在函数的 options 参数中,我们给出 { month: 'long' }。toLocaleDateString('en-US', { month: 'long' }) 的输出现在将是月份名称,即完整的月份名称。然后我们切换 toLocaleDateString('en-US', { month: 'long' }) 函数的完整月份名称输出。

window.onload =
    function() {
  findQuarter('2021-08-08');
  findQuarter('2021-05-12');
  findQuarter('2021-02-28');
  findQuarter('2021-11-30');
  findQuarter('2021-21-30');
}

function findQuarter(dateString) {
  var monthName =
      new Date(dateString).toLocaleDateString('en-US', {month: 'long'});
  switch (true) {
    case['January', 'February', 'March'].includes(monthName):
      console.log('First Quarter');
      break;
    case['April', 'May', 'June'].includes(monthName):
      console.log('Second Quarter');
      break;
    case['July', 'August', 'September'].includes(monthName):
      console.log('Third Quarter');
      break;
    case['October', 'November', 'December'].includes(monthName):
      console.log('Fourth Quarter');
      break;
    default:
      console.log('Invalid date');
      break;
  }
}

输出:

Third Quarter
Second Quarter
First Quarter
Fourth Quarter
Invalid date

在上面的代码中,我们使用了 switch(true) 语句。在 case 子句中,我们有字符串比较。我们为每个季度创建了一个临时的月份数组,并将它们添加到每个案例中。然后我们检查 monthName 在季度数组中是否可用。如果找到,它将记录季度的名称。如果日期无效,toLocaleDateString('en-US', { month: 'long' }) 函数将输出 Invalid Date。这个场景被 default 块捕获,因为 Invalid Date 字符串将与保存季度月份名称的预定义数组不匹配。因此,我们在这里顺利处理无效日期的情况。

注意
我们还可以使用 .indexOf() 代替 .includes() 或 find() 函数来支持多个浏览器。Internet Explorer 不支持 .includes() 和 find() 函数。

使用 Javascript 中的逻辑表达式处理 Switch 中的多个案例

正如我们在数学和字符串表达式中看到的那样,我们还可以在 switch-case 块中的 multiple cases 中使用逻辑运算符。在月份示例中,我们将使用逻辑 OR 运算符 || 用于确定月份名称是否在特定季度中。让我们参考以下代码。

window.onload =
    function() {
  findQuarter('2021-08-08');
  findQuarter('2021-05-12');
  findQuarter('2021-02-28');
  findQuarter('2021-11-30');
  findQuarter('2021-21-30');
}

function findQuarter(dateString) {
  var monthName =
      new Date(dateString).toLocaleDateString('en-US', {month: 'long'});
  switch (true) {
    case (
        monthName === 'January' || monthName === 'February' ||
        monthName === 'March'):
      console.log('First Quarter');
      break;
    case (monthName === 'April' || monthName === 'May' || monthName === 'June'):
      console.log('Second Quarter');
      break;
    case (
        monthName === 'July' || monthName === 'August' ||
        monthName === 'September'):
      console.log('Third Quarter');
      break;
    case (
        monthName === 'October' || monthName === 'November' ||
        monthName === 'December'):
      console.log('Fourth Quarter');
      break;
    default:
      console.log('Invalid date');
      break;
  }
}

输出:

Third Quarter
Second Quarter
First Quarter
Fourth Quarter
Invalid date

在代码中,我们检查 monthName 值是否等于一个季度的月份。因此,我们安慰季度的名称。在这里,我们也处理无效日期的情况,因为它不满足 case 子句中编码的任何条件,并且会落入 default 块,然后将 Invalid date 打印到浏览器控制台。