gpt4 book ai didi

if-statement - IF语句-如何减少/简化源代码量

转载 作者:行者123 更新时间:2023-12-03 17:20:37 25 4
gpt4 key购买 nike

我在尝试减少我的函数的这段代码时遇到麻烦:

checkData(day, month, year, area)
{
if(area == "year" && year == this.year)
return true;

if(area == "month" && month == this.div && year == this.year)
return true;

if(area == "day" && day == this.day && month == this.div && year == this.year)
return true;

return false;
}


如何简化/减少这些IF子句的源代码量?

最佳答案

您的if子句可以重写为:

checkData(day, month, year, area)
{
if(year == this.year) {
if(area == "year") return true;
if(month == this.div) {
if(area == "month") return true;
if(day == this.day) {
if(area == "day") return true;
return false;
}
}
}
}


然后:

checkData(day, month, year, area)
{
if(year != this.year) return false;
if(area == "year") return true;
if(month != this.div) return false;
if(area == "month") return true;
if(day != this.day) return false;
return area == "day";
}


根据编程语言(例如C ++),另一种可能的语法:

checkData(day, month, year, area)
{
return
year != this.year ? false :
area == "year" ? true :
month != this.div ? false :
area == "month" ? true :
day != this.day ? false :
area == "day";
}


然后可以将其写成一行:

checkData(day, month, year, area)
{
return year != this.year ? false : area == "year" ? true : month != this.div ? false : area == "month" ? true : day != this.day ? false : area == "day";
}


某些语言支持这种语法(例如C#):

checkData(day, month, year, area) => year != this.year ? false : area == "year" ? true : month != this.div ? false : area == "month" ? true : day != this.day ? false : area == "day";

关于if-statement - IF语句-如何减少/简化源代码量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51474383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com