萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 根據生日判斷星座:日期區間對照表與可維護資料驅動實作

星座日期區間表(陽曆)

星座起始結束
摩羯座12-2201-19
水瓶座01-2002-18
雙魚座02-1903-20
白羊座03-2104-19
金牛座04-2005-20
雙子座05-2106-21
巨蟹座06-2207-22
獅子座07-2308-22
處女座08-2309-22
天秤座09-2310-22
天蠍座10-2311-21
射手座11-2212-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` 分支,減少邏輯錯誤與修改成本。

copyright © 萬盛學電腦網 all rights reserved