如何避免混乱的嵌套if-else或开关
How to avoid messy nested if-else or switch
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(如果组合的数量不是那么多,请尝试使用HashMap
或Map
或任何等效的组合,并预先填充可能的组合,以便在使用时只需调用hashMap[key]
,最多1个for
循环,然后相应地采取行动,而不是嵌套循环
3(只要有可能,你也可以将它们分解成更小的独立函数,这些函数一次只依赖于一个(或至少更少(的元素(而不是所有元素(。
4(考虑创建一个适当的类并使用Tree
结构来解决它
相关文章:
- 如何在ReactJS JSX中执行嵌套的if-else语句
- Javascript Return and if/else
- JavaScript if-else 速记错误
- 如何检查if/else语句中的随机条件
- 在javascript中创建数组,而不是if.else
- Javascript If else 只返回 TRUE 或只返回 FALSE
- jquery if else不返回警报消息
- 在Javascript中为if/else语句添加OR
- If Else Java Script HTML
- jQuery/Javascript foreach If/Else |如果为空(不执行任何操作)Else(显示forea
- 我应该如何应用if-else条件来向具有不同用户角色的人显示不同的菜单
- geoTest函数-创建if/else语句
- JavaScript中的温度转换器(IF ELSE条件)
- Jquery/Javascript使用IF/ELSE语句更改img SRC
- 是否有一个jQuery函数来“快捷方式”if/else开关
- 如何避免混乱的嵌套if-else或开关
- 语法错误:If else三元运算符中的ES6开关大小写
- 使用开关、三进制或对象代替if/else用于“;步骤“;事件此动画
- 如何在没有ng开关的情况下处理角ng显示中的if else情况
- 执行if-else,开关或基于映射的条件