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

جواب «The Bill» چالش 4 از جلسه‌ی 23

سؤال

دکمه‌ها چای (3 سکه) و کیک (5 سکه) به سفارش اضافه می‌کنند، ولی total همیشه 0 است.
به‌جای const total = 0; با یک حلقه‌ی for ... of روی items، قیمت‌ها را جمع بزن.

راهنما

let total = 0; و بعد for (const item of items) { total += item.price; }

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.big { font-size: 40px; }
ul { list-style: none; padding: 0; }
li { margin: 6px 0; }
</style>

<div id="root" dir="ltr"></div>

<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";

function App() {
  const [items, setItems] = useState([]);

  let total = 0;
  for (const item of items) {
    total += item.price;
  }

  function add(name, price) {
    setItems([...items, { id: items.length + 1, name: name, price: price }]);
  }

  return (
    <div>
      <button id="tea" onClick={() => add("Tea", 3)}>Tea</button>
      <button id="cake" onClick={() => add("Cake", 5)}>Cake</button>
      <ul id="list">
        {items.map((item) => (
          <li key={item.id}>{item.name}: {item.price}</li>
        ))}
      </ul>
      <p id="total" className="big">Total: {total}</p>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن