بتل کد Battle Codeدارد باز می‌شود…

Find the Bug چالش 5 از جلسه‌ی 37، سخت

این برنامه‌ی جاوااسکریپت قیمت‌ها را جمع می‌کند. در جاوااسکریپت می‌نوشت Count: undefined و Total: 520. دو باگ پنهان دارد!
۱. به prices نوع بده (number[])، به ورودی add هم، و نوع خروجی تابع‌ها را بنویس.
۲. خط‌های قرمز تازه هر دو باگ را نشان می‌دهند. درستشان کن.
اول برنامه باید بنویسد Count: 2 و Total: 25. بعد از یک کلیک: Count: 3 و Total: 35.

<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 = [];

function add(price) {
  prices.push(price);
}

function total() {
  let sum = 0;
  for (const p of prices) {
    sum = sum + p;
  }
  return sum;
}

function press() {
  add(10);
  show("Count: " + prices.lenght);
  show("Total: " + total());
}

add(5);
add("20");
show("Count: " + prices.lenght);
show("Total: " + total());
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 37: اسباب‌کشی، قدم اول · چالش بعدی: The Piggy Bank

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js