| 星座 | 起始 | 結束 |
|---|---|---|
| 摩羯座 | 12-22 | 01-19 |
| 水瓶座 | 01-20 | 02-18 |
| 雙魚座 | 02-19 | 03-20 |
| 白羊座 | 03-21 | 04-19 |
| 金牛座 | 04-20 | 05-20 |
| 雙子座 | 05-21 | 06-21 |
| 巨蟹座 | 06-22 | 07-22 |
| 獅子座 | 07-23 | 08-22 |
| 處女座 | 08-23 | 09-22 |
| 天秤座 | 09-23 | 10-22 |
| 天蠍座 | 10-23 | 11-21 |
| 射手座 | 11-22 | 12-21 |
const ZODIAC = [
{ name: "摩羯座", start: [12, 22], end: [1, 19] },
{ name: "水瓶座", start: [1, 20], end: [2, 18] },
{ name: "雙魚座", start: [2, 19], end: [3, 20] },
{ name: "白羊座", start: [3, 21], end: [4, 19] },
{ name: "金牛座", start: [4, 20], end: [5, 20] },
{ name: "雙子座", start: [5, 21], end: [6, 21] },
{ name: "巨蟹座", start: [6, 22], end: [7, 22] },
{ name: "獅子座", start: [7, 23], end: [8, 22] },
{ name: "處女座", start: [8, 23], end: [9, 22] },
{ name: "天秤座", start: [9, 23], end: [10, 22] },
{ name: "天蠍座", start: [10, 23], end: [11, 21] },
{ name: "射手座", start: [11, 22], end: [12, 21] },
];
/**
* 判斷星座
* @param {number} month 1-12
* @param {number} day 1-31
* @returns {string} 星座名稱
*/
function getZodiac(month, day) {
// 處理跨年星座(摩羯座)
if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) {
return "摩羯座";
}
// 其餘星座:起始月份相同或下個月
for (const z of ZODIAC) {
if (z.name === "摩羯座") continue;
const [sm, sd] = z.start;
const [em, ed] = z.end;
if ((month === sm && day >= sd) || (month === em && day <= ed)) {
return z.name;
}
}
return "未知";
}
// 測試
console.log(getZodiac(1, 15)); // 摩羯座
console.log(getZodiac(1, 20)); // 水瓶座
console.log(getZodiac(2, 18)); // 水瓶座
console.log(getZodiac(2, 19)); // 雙魚座
console.log(getZodiac(12, 21)); // 射手座
console.log(getZodiac(12, 22)); // 摩羯座
<label>月份 <select id="selMonth"></select></label>
<label>日期 <select id="selDay"></select></label>
<output id="zodiacResult"></output>
<script>
const $m = document.getElementById("selMonth");
const $d = document.getElementById("selDay");
const $out = document.getElementById("zodiacResult");
function fillMonths() {
for (let m = 1; m <= 12; m++) {
$m.add(new Option(`${m} 月`, m));
}
}
function fillDays(month) {
$d.innerHTML = "";
const days = new Date(2024, month, 0).getDate(); // 取該月天數
for (let d = 1; d <= days; d++) {
$d.add(new Option(`${d} 日`, d));
}
}
function updateZodiac() {
const m = +$m.value, d = +$d.value;
if (m && d) $out.textContent = getZodiac(m, d);
}
$m.addEventListener("change", () => { fillDays(+$m.value); updateZodiac(); });
$d.addEventListener("change", updateZodiac);
fillMonths();
fillDays(new Date().getMonth() + 1);
$m.value = new Date().getMonth() + 1;
$d.value = new Date().getDate();
updateZodiac();
</script>
若需**農曆生日對應星座**,需先用農曆庫(如 `lunar-calendar`)轉陽曆,再套用上述邏輯。
星座判斷本質是**日期區間比對**。將區間資料表驅動化,邏輯集中在單一 `getZodiac` 函式,維護極簡(僅需更新陣列)。避免寫 12 個 `if` 分支,減少邏輯錯誤與修改成本。