星座判斷本質上就是一堆日期區間的條件判斷,只要把每個星座的起訖日寫清楚即可。
function xingzuo() {
var date = document.getElementById("txtDay").value;
var month = document.getElementById("txtMonth").value;
with (document.getElementById("txtXZ")){
if (month == 1 && date >= 20 || month == 2 && date <= 18) { value = "水瓶座"; }
if (month == 1 && date > 31) { value = "Huh?"; }
if (month == 2 && date >= 19 || month == 3 && date <= 20) { value = "雙魚座"; }
if (month == 2 && date > 29) { value = "Say what?"; }
if (month == 3 && date >= 21 || month == 4 && date <= 19) { value = "白羊座"; }
if (month == 3 && date > 31) { value = "OK. Whatever."; }
if (month == 4 && date >= 20 || month == 5 && date <= 20) { value = "金牛座"; }
if (month == 4 && date > 30) { value = "I'm soooo sorry!"; }
if (month == 5 && date >= 21 || month == 6 && date <= 21) { value = "雙子座"; }
if (month == 5 && date > 31) { value = "Umm ... no."; }
if (month == 6 && date >= 22 || month == 7 && date <= 22) { value = "巨蟹座"; }
if (month == 6 && date > 30) { value = "Sorry."; }
if (month == 7 && date >= 23 || month == 8 && date <= 22) { value = "獅子座"; }
if (month == 7 && date > 31) { value = "Excuse me?"; }
if (month == 8 && date >= 23 || month == 9 && date <= 22) { value = "室女座"; }
if (month == 8 && date > 31) { value = "Yeah. Right."; }
if (month == 9 && date >= 23 || month == 10 && date <= 22) { value = "天秤座"; }
if (month == 9 && date > 30) { value = "Try Again."; }
if (month == 10 && date >= 23 || month == 11 && date <= 21) { value = "天蠍座"; }
if (month == 10 && date > 31) { value = "Forget it!"; }
if (month == 11 && date >= 22 || month == 12 && date <= 21) { value = "人馬座"; }
if (month == 11 && date > 30) { value = "Invalid Date"; }
if (month == 12 && date >= 22 || month == 1 && date <= 19) { value = "摩羯座"; }
if (month == 12 && date > 31) { value = "No way!"; }
}
}
這份寫法有兩個可以改進的地方。第一,每個星座都拆成兩個 if,其中「日期超過該月天數」的判斷其實可以統一在最前面做一次月份天數驗證,不必散落在各處;第二,with 語句在嚴格模式下已被禁用,也容易讓作用域變得難以追蹤,改成 var el = document.getElementById("txtXZ"); el.value = ... 會更清楚。
另外提醒一個邏輯細節:像「3 月 21 日」這種跨月邊界,用 month == 3 && date >= 21 || month == 4 && date <= 19 判斷時,因為 && 優先於 ||,實際運算順序是正確的,但加上括弧會讓意圖更明確、也更不容易在修改時出錯。