如何避免混乱的嵌套if-else或开关

How to avoid messy nested if-else or switch

本文关键字:if-else 开关 嵌套 何避免 混乱      更新时间:2023-09-26
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(如果可以制定动作,那么您应该创建公式,而不是创建嵌套的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],最多1个for循环,然后相应地采取行动,而不是嵌套循环

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

4(考虑创建一个适当的类并使用Tree结构来解决它