gpt4 book ai didi

javascript - 简化具有多个条件的变量的条件 OR ​在 Java 或 Javascript 中

转载 作者:行者123 更新时间:2023-11-28 17:06:59 25 4
gpt4 key购买 nike

我有以下代码,我想知道是否有更好的方法来简化它。
我需要使用简单的数据结构(是的,对于每个,等等)

function amountDayMonth(month) {
let amountDayMonth
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
amountDayMonth = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
amountDayMonth = 30;
} else if(month == 2) {
amountDayMonth = 28;
}
return amountDayMonth;
}


谢谢!

最佳答案

到目前为止最简单的解决方案是滥用 Date 对象

function amountDayMonth(month) {
return new Date(2019, month, 0).getDate();
}

月份是从 0 开始的,因此使用月份,您将创建下个月第 0 天的日期,这是该月的最后一天......这是该月的长度

那么如果二月是闰年,则需要修复它

function amountDayMonth(year, month) {
return new Date(year, month, 0).getDate();
}
console.log(amountDayMonth(2019, 4)); // 30
console.log(amountDayMonth(2019, 2)); // 28
console.log(amountDayMonth(2020, 2)); // 29
console.log(amountDayMonth(2019,12)); // 31

完成

不需要 if 或 switch

关于javascript - 简化具有多个条件的变量的条件 OR ​在 Java 或 Javascript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55623585/

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