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

جواب «Don't Stop» چالش 1 از جلسه‌ی 39

سؤال

این برنامه اسم اتاق را از متن JSON داخل کادر می‌خواند. ولی اگر متن خراب باشد، خطا می‌دهد و هیچ چیزی نمی‌نویسد.
دو خط داخل read را در try { } بگذار و در catch (error) { } در خط msg بنویس Bad text.

راهنما

شکلش این است: try { ...دو خط قبلی... } catch (error) { line.textContent = "Bad text"; }

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#box { width: 280px; max-width: 100%; }
</style>

<input id="box" value='{"name":"Kitchen"}'>
<button id="read" onclick="read()">Read</button>
<p id="msg"></p>

<script>
let box = document.getElementById("box");
let line = document.getElementById("msg");

function read() {
  try {
    let room = JSON.parse(box.value);
    line.textContent = room.name;
  } catch (error) {
    line.textContent = "Bad text";
  }
}
</script>

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