Restore a Backup چالش 6 از جلسهی 17، متوسط
حالا برگرداندن پشتیبان. تابع restore() را بنویس: متن #backup را داخل try با JSON.parse بخوان. اگر نتیجه آرایه نبود (Array.isArray)، #msg بنویسد A backup must be a list. و کاری نکند. اگر آرایه بود، آن را در words بگذارد، با salam.save("words", words) ذخیره کند، render() کند و بنویسد Restored 3 words. اگر متن خراب بود، در catch بنویسد This backup is broken.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Word Book</title>
<style>
body { font-family: sans-serif; margin: 0; }
header { background-color: #1e88e5; color: white; padding: 12px 16px; }
.app { max-width: 420px; margin: 0 auto; padding: 16px; }
button, input, textarea { font-size: 16px; min-height: 44px; }
textarea { width: 100%; box-sizing: border-box; }
</style>
</head>
<body>
<div class="app">
<h1>Word Book</h1>
<ul id="words"></ul>
<p><label for="backup">Paste a backup here</label></p>
<textarea id="backup" rows="3"></textarea>
<button id="restoreBtn" onclick="restore()">Restore</button>
<p id="msg"></p>
</div>
<script>
let words = salam.load("words", []);
function render() {
let list = document.getElementById("words");
list.innerHTML = "";
for (let word of words) {
let li = document.createElement("li");
li.textContent = word;
list.appendChild(li);
}
}
function restore() {
// try JSON.parse, check it is a list, save, render
}
render();
</script>
</body>
</html>
راهنما و جواب این چالش · برگشت به درس جلسهی 17: خروجی و نصب · چالش بعدی: Portable Water Counter
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js