在switch case语句中检测2个变量值的4个排列 [英] detect 4 permutations of 2 variable values in a switch case statement

查看:645
本文介绍了在switch case语句中检测2个变量值的4个排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个变量, width height 作为整数。任何这些可以是正或负(不是零)。所以自然有4种情况;

I have 2 variables, width and height as integers. Any of these can be positive or negative (not zero). So naturally there are 4 cases;


  1. width> 0&&&高度> 0

  2. width> 0&&高度< 0

  3. width< 0&&高度> 0

  4. width< 0&&高度< 0

  1. width > 0 && height > 0
  2. width > 0 && height < 0
  3. width < 0 && height > 0
  4. width < 0 && height < 0

现在,我想对这4种情况采取不同的操作,而不使用4个if语句。

Now I want to take different action on each of these 4 cases without using 4 if statements.

有一种方法来聚合这些案例,以便它可以作为一个简单的开关案例

Is there a way to aggregate these cases so that it can be put as a simple switch case

switch( aggregate ){
  case 1:
  case 2:
  case 3:
  case 4:
}

如果没有比使用 if 为每个,然后在3D空间中,你有3个长度(x,y,z),将有27 如果被阻止。

If there is no better way than using if for each then in 3D space you have 3 lengths (x,y,z) and there will be 27 if blocks.

如果重要的话,我使用 javascript

I'm using javascript if that matters.

推荐答案

javascript 中,这很容易,只需将条件颠倒过来:

In javascript this is quite easy, just turn the condition upside down:

switch(true)
{
    case (width > 0 && height > 0):
        break;
    case (width > 0 && height < 0):
        break;
    case (width < 0 && height > 0):
        break;
    case (width < 0 && height < 0):
        break;

    default:

}

这是一个简单的证明: http://jsfiddle.net/avuxj/

Here's a simple proof: http://jsfiddle.net/avuxj/

这篇关于在switch case语句中检测2个变量值的4个排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆