多个条件的替代方法 [英] alternative approaches to multiple if else conditions

查看:45
本文介绍了多个条件的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个条件需要检查和执行,如下所示.

I have multiple conditions to be checked and executed like below.

if (date == current_date && source === "s3") {
    table_name = "Table1";
} else if (date == current_date && source !== "s3") {
    table_name = "Table2";
} else if (date !== current_date && source === "s3") {
    table_name = "Table3";
} else if (date !== current_date && source !== "s3") {
    table_name = "Table4";
}

我认为使用switch语句在这里没有意义,因为我们没有针对switch表达式评估case语句表达式.

I think using switch statement doesn't make sense here since we are not evaluating case statement expression against switch expression.

那么可以使用多个if else语句或其他更好的替代方法吗?

So is it okay to go with multiple if else statements or any better alternative approach?

推荐答案

您的代码是100%不错的选择.有点难读.您可以将通用代码提取到变量中,以使其更具可读性

Your code is 100% a good option. It is just a bit hard to read. You can pull out common code into variable to make it more readable

var isCurrent = date == current_date;
var isS3 = source === "s3";

if (isCurrent && isS3) {
    table_name = "Table1";
} else if (isCurrent && !isS3) {
    table_name = "Table2";
} else if (!isCurrent && isS3) {
    table_name = "Table3";
} else {
    table_name = "Table4";
}

其他选择是使用三元运算符

Other option is to use ternary operators

var isCurrent = date == current_date;
var isS3 = source === "s3";

if (isCurrent) {
    table_name = isS3 ? "Table1" : "Table2";
} else {
    table_name = isS3 ? "Table3" : "Table4";
}

可能是一个三元组,但是有点难以理解

It could be one big ternary, but it is a bit unreadable

var isCurrent = date == current_date;
var isS3 = source === "s3";

table_name = isCurrent ? 
    (isS3 ? "Table1" : "Table2") :
    (isS3 ? "Table3" : "Table4");

这篇关于多个条件的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆