如何避免凌乱的嵌套if-else或switch

时间:2015-12-14 10:02:56

标签: javascript if-statement nested switch-statement polymorphism

Function AM()
{
  var source = new Array("External","Chassis","Internal");
  var shape = new Array("Sine","Square", "Ramp","Nramp","Triangle","ARB");
  var depth = new Array ("100","0","50");
  var frequency = new Array("100","0.002","20000","1000");

  var currentSource;
  var currentShape;
  var currentDepth;
  var currentFrequency;

  for (var item in source)
  {
    currentSource = source[item];
    FG_AMSource().Keys(source[item] );

    for (var item in shape)
    {
      currentShape = shape[item];
      FG_AMShape().Keys(shape[item] );

      for (var item in depth)
      {
        currentDepth = depth[item];
        FG_AMDepth().Keys(depth[item]);

        for (var item in frequency)
        {
          currentFrequency = item;
          FG_AM_Frequency().Keys(frequency[item]);
          CheckImage2(currentSource, currentShape,currentDepth, currentFrequency);
        }// shape
      }// depth
    }// shape
  }//source
}

FG_AMSource()是一个允许我设置设置的功能。通过我在这里,我能够遍历源,形状,深度和频率的所有组合。 我的问题在于CheckImage2功能。我得到的每个组合,我必须调用此CheckImage2函数,传入当前的源,形状,深度和频率,然后进行相应的检查。因此,在我的CheckImage2函数中,它看起来像

Function CheckImage2(currentSource, currentShape, currentDepth, currentFrequency)
{
    switch (currentSource)
        case "External":
            switch (currentShape)
                case "Sine":
                    switch (currentDepth)
                        case "100":
                            switch (currentFrequency)
                                case "100": //External+Sine+100+100
                                case "0.002": //External+Sine+100+0.002
                                //etc etc etc you get the idea
                                //and I need to include all possible combinations
}

我该怎么办?

1 个答案:

答案 0 :(得分:2)

有几种方法可以解决这个问题:

1)如果操作可以制定,那么您应该创建公式,而不是创建嵌套的for循环或switch。像

这样的东西
Function CheckImage2(currentSource, currentShape, currentDepth, currentFrequency)
{
    //example, suppose it can be formulated as a string
    string formulatedString = currentSource + currentShape + currentDepth + currentFrequency; 
    //do something else, because things can be formulated instead of listed
}

这是因为你真正需要的是一个处理器/函数,它可以采用任何组合。

2)如果组合的数量不是很多,请尝试使用HashMapMap或等效的预先填充可能的组合,以便您只需要调用hashMap[key]并且最多只需要for循环,然后相应地执行操作,而不是使用嵌套循环

3)只要有可能,您也可以将它们分解为较小的独立函数,这些函数一次只依赖于一个(或至少更少)元素(而不是所有元素)。 / p>

4)考虑创建一个合适的类和使用Tree结构来解决它