每年有12个月,有四个季度,那么,我们如何判断用户输入的某个月份属于哪个季节呢?接下来,济南网站建设小编就来为大家分享一个JavaScript小案例,根据用户输入的月份自动判断,该月份属于哪个季节,有需要的朋友可以过来参考一下。
关键代码:
<div class="box">
<input type="number" id="monthInp" placeholder="输入1-12的月份数字">
<button onclick="getQuarter()">判断季度</button>
<div id="res"></div>
</div>
<script>
function getQuarter() {
const month = Number(document.getElementById('monthInp').value);
const resBox = document.getElementById('res');
// 校验输入合法性
if (isNaN(month) || month < 1 || month > 12) {
resBox.innerText = '请输入1~12之间有效的月份数字';
resBox.style.color = 'red';
return;
}
resBox.style.color = '#000';
let quarter;
// 条件判断区分季度
if (month >= 1 && month <= 3) {
quarter = '第一季度(1、2、3月)';
} else if (month >= 4 && month <= 6) {
quarter = '第二季度(4、5、6月)';
} else if (month >= 7 && month <= 9) {
quarter = '第三季度(7、8、9月)';
} else {
quarter = '第四季度(10、11、12月)';
}
resBox.innerText = `${month}月属于${quarter}`;
}
// 数学简化算法(无if,常用后台计算)
function getQuarterByMath(monthNum) {
return Math.ceil(monthNum / 3);
}
console.log(getQuarterByMath(5)); // 输出 2
</script>
评论