如果执行了任何 if + else if + else if...
,我想运行代码:
if(){
...
}else if(){
...
}else if(){
...
}
//run something if ANY of the above was executed
我可以添加我想要在每个 if
或 else if
上执行的行,但这会是太多垃圾邮件。
我所做的如下:
temp=i;//store a copy
i=-1;//make the change
if(){
...
}else if(){
...
}else if(){
...
}else{
i=temp//restore if none was executed
}
无论发生什么情况,上面都会应用更改,并使用 else
撤消此更改。这工作正常,但我真的很担心这段代码的可读性
我还缺少其他更具可读性的替代方案吗?
最佳答案
好吧,你总是可以做到
any=true;
if (...) {
} else if (...) {
} else if (...) {
} else {
any = false;
// or: return, if you are inside a function!
}
if (any) {
// one of the ifs was executed.
}
如果你使用函数来包装它,你也可以在最后的 else 中return
。这可能是最干净的版本。
关于javascript - 如果执行了 "if...else if"中的任何一个,则运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132724/