JavaScript使用函数、switch_case完成给定日期判断这是本年中的第几天

1:分别用三个弹框 定义赋值年,月,天。Number()把字符串型转为数值型

var year = Number(prompt("请输入一个年份:"))
			var month = Number(prompt("请输入一个月份:"))
			var day = Number(prompt("请输入一天:"))

2: if else判断是否是闰年

function isLeapYear(year) {
if (year % 4 == 0 && year % 100 != 0|| year % 400 == 0) {
					return true;
				} else {
					return false;
				}
			}

3: switch分支 有参数有返回值

function getDaysByDate(year, month, day) {
				//定义一个总天数
				var days = 0
				switch (month) {
					case 12:
						//11月天数
						days += 30
					case 11:
						//10月天数
						days += 31
					case 10:
						//9月天数
						days += 30
					case 9:
						//8月天数
						days += 31
					case 8:
						//7月天数
						days += 30
					case 7:
						//6月天数
						days += 30
					case 6:
						//5月天数
						days += 31
					case 5:
						//4月天数
						days += 30
					case 4:
						//3月天数
						days += 31
					case 3:
						//2月天数
						days += isLeapYear(year)?29:28
					case 2:
						//1月天数
						days += 31
					case 1:
						//当前月天数
						days += day
						break
					default:
						break;
				}
				return days
			}

4:输出

			document.write(year + "年" + month + "月" + day + "日是本年的第" + result + "天")

5:思路总结

①分别用三个弹框 定义赋值年,月,天。Number()把字符串型转为数值型

②if else判断是否是闰年

③switch分支 有参数有返回值

④输出

⑤重难点:对于月份天数的计算

6:全部代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			var year = Number(prompt("请输入一个年份:"))
			var month = Number(prompt("请输入一个月份:"))
			var day = Number(prompt("请输入一天:"))
			var result = getDaysByDate(year, month, day);
			function isLeapYear(year) {
				//判断是否是闰年
				if (year % 4 == 0 && year % 100 != 0|| year % 400 == 0) {
					return true;
				} else {
					return false;
				}
			}

			function getDaysByDate(year, month, day) {
				//定义一个总天数
				var days = 0
				switch (month) {
					case 12:
						//11月天数
						days += 30
					case 11:
						//10月天数
						days += 31
					case 10:
						//9月天数
						days += 30
					case 9:
						//8月天数
						days += 31
					case 8:
						//7月天数
						days += 30
					case 7:
						//6月天数
						days += 30
					case 6:
						//5月天数
						days += 31
					case 5:
						//4月天数
						days += 30
					case 4:
						//3月天数
						days += 31
					case 3:
						//2月天数
						days += isLeapYear(year)?29:28
					case 2:
						//1月天数
						days += 31
					case 1:
						//当前月天数
						days += day
						break
					default:
						break;
				}
				return days
			}
			document.write(year + "年" + month + "月" + day + "日是本年的第" + result + "天")
		</script>
	</head>
	<body>
	</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值