Throw a Kind Message چالش 4 از جلسهی 17، متوسط
تابع readGoal(text) را بنویس که عدد هدف آب را برگرداند، ولی اگر text خالی بود یا عدد نبود با throw new Error("Please type a number.") خطا بدهد، و اگر کمتر از ۱ بود با "The goal must be 1 or more.". در setGoal() آن را داخل try صدا بزن: اگر درست بود #msg بنویسد Goal: 8 glasses، و در catch همان error.message را نشان بدهد. (کادر #goal از نوع text با inputmode="numeric" است تا هر چیزی بشود در آن نوشت.)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Water</title>
<style>
body { font-family: sans-serif; margin: 0; }
header { background-color: #0288d1; color: white; padding: 12px 16px; }
.app { max-width: 420px; margin: 0 auto; padding: 16px; }
button, input, textarea { font-size: 16px; min-height: 44px; }
textarea { width: 100%; box-sizing: border-box; }
</style>
</head>
<body>
<div class="app">
<p><label for="goal">My goal (glasses)</label></p>
<input id="goal" inputmode="numeric" placeholder="8">
<button id="set" onclick="setGoal()">Set goal</button>
<p id="msg"></p>
</div>
<script>
function readGoal(text) {
// throw an Error for empty text, for text that is not a number, and for less than 1
return Number(text);
}
function setGoal() {
let goal = readGoal(document.getElementById("goal").value);
document.getElementById("msg").textContent = "Goal: " + goal + " glasses";
}
</script>
</body>
</html>
راهنما و جواب این چالش · برگشت به درس جلسهی 17: خروجی و نصب · چالش بعدی: Make a Backup
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js