在对象文字函数中需要等效于默认的 switch case

Need an equivalent of the default of switch case in an object literal function

在 switch case 中,默认情况不是预期的情况。我不得不用对象文字函数替换我的 switch case 以减少圈复杂度。

function test(){
  const options = getOptions();
  switch(options){
   case 'a':
       return 'foo';
   case 'b'
       return 'bar';
   default:
       return 'Nothing';
  }
}

我写的替换函数:

function test(){
  const options = getOptions();
   return {
      'a': 'foo',
      'b': 'bar',
      '': 'Nothing',
      null: 'Nothing',
      undefined: 'Nothing'
   }[options]
}

test();

问题是除 a、b 之外的任何字母表都将 return 未定义,这与默认处理所有其他选项的 switch case 不同。

我试过这个:

function test(){
  const options = getOptions();
  const default = new RegExp([^c-zC-Z], 'g');
   return {
      'a': 'foo',
      'b': 'bar',
      '': 'Nothing',
      null: 'Nothing',
      undefined: 'Nothing',
      default: 'Nothing'
   }[options]
}

上面的正则表达式解决了我对覆盖 'a'、'b' 以外的所有问题的担忧,但范围不在 return 语句内,默认情况下无法识别。请建议默认情况。

你可以试试这个方法

function test(){
  const result = {
      'a': 'foo',
      'b': 'bar'
   }[getOptions()];
  return result ? result : 'Nothing';
}

test();