【问题标题】:Javascript multiple decisions in switch case开关案例中的Javascript多项决策
【发布时间】:2018-03-03 10:37:05
【问题描述】:

我很难运行在 switch case 中检查两个条件的代码,因为在 javascript 中此代码打印“未知”

['police',false]!=['police',false]

有没有办法使用switch-case 而不是嵌套的ifs 来实现这段代码?

var option='police';
var urgent=false;

switch([option,urgent])
{
case ['police',true]:
       console.log('police,true');
       call_police_urgent();
       break;
case ['police',false]:
       console.log('police,false');
       call_police();
       break;
case ['hospital',true]:
       console.log('hospital,true');
       call_hospital_urgent();
       break;
case ['hospital',false]:
       console.log('hospital,false');
       call_hospital();
       break;
case ['firestation',true]:
       console.log('firestation,true');
       call_firestation_urgent();
       break;
case ['firestation',false]:
       console.log('firestation,false');
       call_firestation();
       break;
default:
       console.log('unknown');
}

【问题讨论】:

  • 错字:swtich => switch
  • @georg 谢谢。但主要问题仍然存在
  • @ar2015:是的,见下文
  • @ecg8, 提供的解决方案并不比if好。

标签: javascript node.js


【解决方案1】:

您的代码不起作用,因为一个数组文字永远不会等于另一个,即使它们看起来相同。有很多方法可以解决这个问题,但其中大多数归结为将数组转换为可以比较的东西,例如字符串:

let str = (...args) => JSON.stringify(args);

switch (str(option, urgent)) {
    case str('police', false):
        console.log('police,false');
        break;
    case str('hospital', true):
        console.log('hospital,true');
        break;
    default:
        console.log('unknown');
}

这适用于您的简单情况,但不适用于一般情况,因为并非所有内容都可以字符串化。

【讨论】:

  • 聪明的解决方案!
【解决方案2】:

您可以将选项数组转换为字符串:

var option='police';
var urgent=false;

switch([option,urgent].join())
{
case 'police,true':
       console.log('police,true');
       break;
case 'police,false':
       console.log('police,false');
       break;
case 'hospital,true':
       console.log('hospital,true');
       break;
case 'hospital,false':
       console.log('hospital,false');
       break;
case 'firestation,true':
       console.log('firestation,true');
       break;
case 'firestation,false':
       console.log('firestation,false');
       break;
default:
       console.log('unknown');
}

【讨论】:

  • join 对于这种事情是脆弱的,考虑像['a,b', 'c'] 这样的论点和a,b,c 的情况。
  • @georg 你是对的,而且你提出的解决方案更优雅。
【解决方案3】:

我不知道你想做什么,但是你上面的代码 javascript 引擎和运行时环境对你大喊大叫。

其次,[] 文字可以并且永远不会等于另一个 [] 文字

在这两者之间选择

var option='police';
var urgent=false;

function first_switch(option,urgent) {
    switch(option) {
    case "police":
        if ( urgent )
            console.log('police,true');
        else
            console.log('police,false');
        break;
    case "hospital":
        if ( urgent )
            console.log('hospital,true');
        else
            console.log('hospital,false');
        break;
    case "firestation":
        if ( urgent )
            console.log('firestation,true');
        else
            console.log('firestation,false');
        break;
    default:
        console.log('unknown');
    }
}

function second_switch(option,urgent) {

    if ( urgent ) {

        switch(option) {
        case "police":
        case "hospital":
        case "firestation":
            console.log(`${option}`, "true");
            break;
        default:
            console.log('unknown');
        }

        return ;
    }

    switch(option) {
    case "police":
    case "hospital":
    case "firestation":
        console.log(`${option}`, "false");
        break;
    default:
        console.log('unknown');
    }
}

first_switch(option,urgent);
first_switch(option, true);

second_switch(option, urgent);
second_switch(option, true);

【讨论】:

  • 这是一个 MWE,实际上我不能使用 ${option}。我也想避免if
  • 然后删除`${}`,只留下选项
  • 我更新了代码,以便更好地反映限制。
【解决方案4】:

我们可以在不使用 switch case 的情况下创建相同的功能。我们可以创建如下查找表:

var emergencyLookupTable = {
  police: [{
      case: true,
      fn: call_police_urgent
    },
    {
      case: false,
      fn: call_police
    }
  ],
  hospital: [{
      case: true,
      fn: call_hospital_urgent
    },
    {
      case: false,
      fn: call_firestation_urgent
    }
  ],
  firestation: [{
      case: true,
      fn: call_firestation_urgent
    },
    {
      case: false,
      fn: call_firestation
    }
  ]
}

并将这个对象传递给正在寻找正确案例的emergency

function emergency(lookup, option, urgent) {
  if (lookup[option]) {
    lookup[option]
      .filter(function(obj) {
        return obj.case === urgent
      })
      .forEach(function(obj) {
        obj.fn()
      })
  } else {
    console.log('unknown')
  }
}

emergency(emergencyLookupTable, 'police', true)

工作示例

var emergencyLookupTable = {
  police: [{
      case: true,
      fn: call_police_urgent
    },
    {
      case: true,
      fn: call_police_urgent2
    },
    {
      case: false,
      fn: call_police
    }
  ],
  hospital: [],
  firestation: []
}

function emergency(lookup, option, urgent) {
  if (lookup[option]) {
    lookup[option]
      .filter(function(obj) {
        return obj.case === urgent
      })
      .forEach(function(obj) {
        obj.fn()
      })
  } else {
    console.log('unknown')
  }
}

function call_police_urgent() {
  console.log('call the police!')
}

function call_police_urgent2() {
  console.log('call the police again!')
}

function call_police() {
  console.log('call the police..')
}

emergency(emergencyLookupTable, 'police', true)
emergency(emergencyLookupTable, 'police', false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多