جواب «Find the Bugs» چالش 6 از جلسهی 29
سؤال
هر دکمه باید اتاقِ خودش را روشن و خاموش کند و زیرش نوشته شود چند اتاق روشن است، مثل On: 2. ولی هر دکمهای بزنی آشپزخانه عوض میشود و متنِ پایین هم عجیب است.
دو اشتباه دارد. هر دو را پیدا و درست کن. (راهنمایی: یکی داخلِ find است و یکی در خطی که متن را مینویسد.)
راهنما
در find باید مقایسه کنی، پس === لازم است: r.id === id. و lit یک آرایه است؛ تعدادش lit.length است.
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.house { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; max-width: 340px; margin: 12px auto; }
.room { width: 150px; padding: 18px 0; border-radius: 12px; background: #334155; color: white; }
.room.on { background: #fde047; color: black; }
</style>
<div class="house">
<div id="kitchen" class="room">Kitchen</div>
<div id="bedroom" class="room">Bedroom</div>
<div id="living" class="room">Living room</div>
<div id="bath" class="room">Bath</div>
</div>
<button id="b-kitchen" onclick="toggle('kitchen')">Kitchen</button>
<button id="b-bedroom" onclick="toggle('bedroom')">Bedroom</button>
<button id="b-living" onclick="toggle('living')">Living room</button>
<button id="b-bath" onclick="toggle('bath')">Bath</button>
<p id="msg"></p>
<script>
const rooms = [
{ id: "kitchen", name: "Kitchen", on: false },
{ id: "bedroom", name: "Bedroom", on: false },
{ id: "living", name: "Living room", on: false },
{ id: "bath", name: "Bath", on: false }
];
function draw(room) {
let box = document.getElementById(room.id);
if (room.on) {
box.classList.add("on");
} else {
box.classList.remove("on");
}
}
function drawAll() {
for (const room of rooms) {
draw(room);
}
}
function toggle(id) {
let room = rooms.find((r) => r.id === id);
room.on = !room.on;
drawAll();
let lit = rooms.filter((r) => r.on);
document.getElementById("msg").textContent = `On: ${lit.length}`;
}
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن