在 JavaScript 中查找闰年和非闰年中的第 n 天
问题
我们要求编写一个 JavaScript 函数,该函数采用一个数字作为第一个参数,采用一个布尔值作为第二个参数。
布尔值指定闰年(如果为真)。基于此信息,我们的函数应该返回第 n 天中的日期。
示例
以下是代码 −
const day = 60;
const isLeap = true;
const findDate = (day = 1, isLeap = false) => {
if(day > 366){
return undefined;
};
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if(isLeap){
days[1]++;
};
let i = -1, count = 0;
while(count < day){
i++;
count += days[i];
};
const upto = days.slice(0, i).reduce((acc, val) => acc + val);
const month = months[i];
const d = count - upto;
return `${month}, ${d}`;
};
console.log(findDate(day, isLeap));输出
以下是控制台输出 −
Feb, 29
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP