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>