جواب «Step 3: The Button» چالش 3 از جلسهی 20
سؤال
قدم سوم: حالا صفحه یک دکمهی Next دارد که press() را صدا میزند.
- چهار خط show را پاک کن (هم Light: red و هم سه خط امتحانی).
- تابع draw(): void را بنویس که Light: و رنگ الان را با show مینویسد.
- تابع press(): void را بنویس: light را به next(light) عوض میکند و بعد draw() را صدا میزند.
- در آخر برنامه یک بار draw() را صدا بزن.
اول باید فقط Light: red دیده شود. با هر بار زدن دکمه یک خط تازه میآید: Light: green، Light: yellow، Light: red.
راهنما
function press(): void { light = next(light); draw(); } و در draw: show("Light: " + light);
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>
<button id="go" onclick="press()">Next</button>
<pre id="out"></pre>
<script type="text/typescript">
// 1. the type Light and the box light
type Light = "red" | "green" | "yellow";
let light: Light = "red";
// 2. the function next
function next(now: Light): Light {
switch (now) {
case "red":
return "green";
case "green":
return "yellow";
case "yellow":
return "red";
default: {
const forgot: never = now;
return forgot;
}
}
}
// 3. the button
function draw(): void {
show("Light: " + light);
}
function press(): void {
light = next(light);
draw();
}
draw();
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن