我有这种多嵌套的if-else块。我的理解是,有一种“数据驱动”方法可以帮助消除对代码的需要并精简代码,但是,我还没有足够的经验,因此任何人都可以帮助我重构此代码以“数据驱动”方式工作?
function (arg1) {
if(this.thing[arg1]){
// there is a valid property for this arg1
if(this.thing.a){
// there exists an 'a' propertie also
if(this.thing.a.arg1 == arg1){
// the a property has a property is the same as the arg1
// if this 'a' has a number higher than 0, avoid doing anything
if(this.thing.a.number > 0){
}else{
// 'a' number was 0 or lower, so we do something
this.thing.a = this.thing[arg1];
this.thing.a.arg1 = arg1;
}
}else{
// the' a' is not the arg1
// so we want to use the current arg1!
// but only if its 'number' is lower than 1
if(this.thing.a.number > 0){
}else{
// 'a' number was 0 or lower, so we do something
this.thing.a = this.thing[arg1];
this.thing.a.arg1 = arg1;
}
}
}else{
// there is no thing.a so we set it to arg1
this.thing.a = this.thing[arg1];
this.thing.a.arg1 = arg1;
}
}
}
最佳答案
可以肯定地说,您的逻辑可以归结为:
if (this.thing[arg1]) {
//confirm or set a
this.thing.a = this.thing.a ? this.thing.a : this.thing[arg1];
//if a.arg1 is not thing[arg1] and a.number is less than 1
if (this.thing.a.arg1 !== this.thing[arg1] && this.thing.a.number < 1) {
this.thing.a = this.thing[arg1];
this.thing.a.arg1 = arg1;
}
}
您应该注意的事项:
这个:
if(someNumber > 0){
//do nothing
} else {
//do something
}
永远不会是对的。不要创建空块,不要更改表达式,如下所示:
if (someNumber < 1) {
//do something
}
您重复此代码块3次。保持干燥(不要重复自己)
this.thing.a = this.thing[arg1];
this.thing.a.arg1 = arg1;
如果您发现您正在重复这样的代码,请退后一步,看看如何更改逻辑流程,这样您只需要编写一次代码即可。
关于javascript - 如何重构这个多嵌套的if else块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31485849/