[英]simplify if else statement
I have some functionality dependent on many conditions. 我有一些功能取决于许多条件。 All variables in conditional statements are boolean variables and the code is the following and I don't like it:
条件语句中的所有变量都是布尔变量,代码如下,我不喜欢它:
if (userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Is there a way to make it more understandable and nice? 有没有办法使它更容易理解和更好?
That's about as concise as you're going to get with JavaScript. 这与使用JavaScript一样简洁。 I suppose if you really wanted to, you could create variables to store your binary options:
我想如果您真的想要,可以创建变量来存储二进制选项:
var multiMarketOneSelected = userHasMoreThanOneMarket && isOnlyMarketSelected;
var singleMarketMultiAgency = !userHasMoreThanOneMarket && userHasMoreThanOneAgency;
if (multiMarketOneSelected || singleMarketMultiAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Though I don't really know if you gain much readability from that. 虽然我真的不知道您是否从中获得了更多的可读性。
Your code seems fine, but if you don't like it you could do something like this (note that the only improvement here is style, if you like it better): 您的代码看起来不错,但是如果您不喜欢它,则可以执行以下操作(请注意,如果您更喜欢它,这里唯一的改进就是样式):
function check(){
return {
valid: userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency,
case: [
isOnlyAgencySelected,
noAgencySelected && isOnlyMarketSelected
]
};
}
var conditions = check();
if (conditions.valid) {
if (conditions.case[0]) {
//do case 1
} else if (conditions.case[1]) {
//do case 2
}
}
Some things I would try to make the code more readable: 我会尝试使代码更具可读性的一些事情:
!userHasMoreThanOneMarket
becomes userHasOneMarket
!userHasMoreThanOneMarket
成为userHasOneMarket
isOnlyMarketSelected
sounds redundant to me. isOnlyMarketSelected
对我来说似乎是多余的。 And you are checking it in the outer if-clause and the inner again. return;
return;
statements after each variable to get rid of if-conditions. I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.