於課堂中ALPHA Camp – Yujen教練講解星座計算的模擬,過程中慢慢地從基礎計算進而優化,讓我受益良多,並試將星座計算變更成人工輸入後在合理範圍中進行判斷,來完成靈巧的運算。
1. 我挑戰運用陣列的頭尾銜接,建構循環的星座配對。
2.1 該設計會碰到輸入無效生日時,會歸類到錯誤的星座,故新增規則陣列結合input來確保資料運算正常。
2.2 在寫while迴圈時,發現無法在迴圈內中進行 (let + prompt)的操作,測試程式有break離去,但仍會再進入while迴圈。
-錯誤寫法:
while (1) {
let birthday = prompt(‘請輸入您的生日(格式:民國/月份/日期)’)
}
-正確寫法:
let birthday
while (1) {
birthday = prompt(‘請輸入您的生日(格式:民國/月份/日期)’)
}
3.星座計算機-連續陣列
step1.宣告 星座的名稱陣列
const zodiac = [ '魔羯', '水瓶', '雙魚', '牡羊', '金牛', '雙子', '巨蟹', '獅子', '處女', '天秤', '天蠍', '射手', '魔羯' ]
step2.宣告 星座的日期下限陣列
const limit = [ 19, 18, 20, 19, 20, 20, 22, 22, 22, 22, 21, 21, 19 ]
step3.宣告 星座的日期天數陣列
const day = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31 ]
step4.宣告 需使用的變數
//const birthday = '86/6/40' //判斷日期 //無限循環 let birthday let birthdayArr let month let date
step5.建立while衡ture的迴圈,當輸入日期超過範圍跳出錯誤訊息,並在日期符合之範圍顯示星座名稱
while (1) { birthday = prompt('請輸入您的生日(格式:民國/月份/日期)') birthdayArr = birthday.split('/') month = Number(birthdayArr[1]) date = Number(birthdayArr[2]) if ((month <= zodiac.length) && (date <= day[month])) { break } console.log('您輸入的生日錯誤,請重新輸入,謝謝') } if (date <= limit[month - 1 ]) { console.log(zodiac[month - 1]) } else { console.log(zodiac[month]) }