جواب «Find the Bug» چالش 5 از جلسهی 37
سؤال
این برنامهی جاوااسکریپت قیمتها را جمع میکند. در جاوااسکریپت مینوشت Count: undefined و Total: 520. دو باگ پنهان دارد!
۱. به prices نوع بده (number[])، به ورودی add هم، و نوع خروجی تابعها را بنویس.
۲. خطهای قرمز تازه هر دو باگ را نشان میدهند. درستشان کن.
اول برنامه باید بنویسد Count: 2 و Total: 25. بعد از یک کلیک: Count: 3 و Total: 35.
راهنما
باگ اول: add("20") متن میفرستد، باید add(20) باشد. باگ دوم: lenght غلط است، درستش length است (دو جا).
یک جواب درست
<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()">Add 10</button>
<pre id="out"></pre>
<script type="text/typescript">
let prices: number[] = [];
function add(price: number): void {
prices.push(price);
}
function total(): number {
let sum = 0;
for (const p of prices) {
sum = sum + p;
}
return sum;
}
function press(): void {
add(10);
show("Count: " + prices.length);
show("Total: " + total());
}
add(5);
add(20);
show("Count: " + prices.length);
show("Total: " + total());
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن