用Chatgpt來學習|閏年計算JavaScript
若要判斷年份是否為閏年,請依照下列步驟執行:
- 如果年份被 4 整除,則移至步驟 2。
- 如果年份被 100 整除,則移至步驟 3。
- 年份被 400 整除。
節錄自https://learn.microsoft.com/zh-tw/office/troubleshoot/excel/determine-a-leap-year
方法1:
function isLeapYear(year) { if (year % 4 !== 0) { // If the year is not divisible by 4, it's not a leap year return false; } else if (year % 100 !== 0) { // If the year is divisible by 4 but not by 100, it's a leap year return true; } else if (year % 400 !== 0) { // If the year is divisible by 100 but not by 400, it's not a leap year return false; } else { // If the year is divisible by both 100 and 400, it's a leap year return true; } } // You can call this function with a year as an argument, like this: console.log(isLeapYear(2020)); // Output: true console.log(isLeapYear(2021)); // Output: false
方法2:
function isLeap(year) { if (year % 4 === 0) { if (year % 100 === 0) { if (year % 400 === 0) { return "It is a leap year"; } else { return "It is not a leap year"; } } else { return "It is a leap year"; } } else { return "It is not a leap year"; } }
方法3(最短):
function isLeap(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }