今天看群里一哥們折騰得挺熱乎,手癢隨便寫了一個DEMO,供初學者參考。
重點,寫程序先定注釋,明確思路后再寫具體代碼。
//星座定義 var constellations = [ {"Start":121,"End":220,"Name":"水平座"}, {"Start":221,"End":320,"Name":"雙魚座"}, {"Start":321,"End":420,"Name":"白羊座"}, {"Start":421,"End":520,"Name":"金牛座"}, {"Start":521,"End":620,"Name":"雙子座"}, {"Start":621,"End":720,"Name":"巨蟹座"}, {"Start":721,"End":820,"Name":"獅子座"}, {"Start":821,"End":920,"Name":"處女座"}, {"Start":921,"End":1020,"Name":"天秤座"}, {"Start":1021,"End":1120,"Name":"天蠍座"}, {"Start":1121,"End":1220,"Name":"射手座"} ]; function WhatIsYourConstellation(y,m,d) { /* 判斷日期有效性 1,3,5,7,8,10,12為31天 2月潤年29,非潤年28 4,6,9,11為30天 */ var daysInMonth = [31,99,31,30,31,30,31,31,30,31,30,31]; //檢測年份 if(y < 1970 || y > 2099) return "滾犢子1"; //檢測月份 if(m < 1 || m > 12) return "滾犢子2"; //檢測日期 var mDays = daysInMonth[m-1]; //如果是二月,要根據年份計算天數,不是二月時略過此計算 if(m == 2) { mDays = GetSpecialDays(y) } //判斷日數據是不是在月份的有效天范圍 if(d < 0 || d > mDays) return "滾犢子3"; //好了,走到這一步,說明上面的驗證都TM過了。 //這才判斷是哪一個星座 //星座座標等於m*100 + d var pos = m * 100 + d; for(var i in constellations) { if(pos >= constellations[i].Start && pos <= constellations[i].End) { return constellations[i].Name; } } } //根據年份計算二月天數 function GetSpecialDays(y) { if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) return 29; return 28; }
調用DEMO
<meta http-equiv="content-type" content="text/html;charset=utf-8"> <script src="xx.js"></script> <div id="log"> </div> <script> function testCase(y,m,d) { var p = document.createElement("p"); p.style.color = "red"; p.style.fontSize = "14px"; var data = WhatIsYourConstellation(y,m,d); p.innerText = y + "年" + m + "月" + d + "日的計算結果:" + data; document.getElementById("log").appendChild(p); } testCase(1800,1,1); testCase(2000,-1,1); testCase(2000,13,1); testCase(2000,1,-1); testCase(2000,1,32); testCase(2000,2,32); testCase(2000,2,29); testCase(2001,2,29); </script>
測試結果