Random Quote Generator
你将构建什么
page 使用 quote display 区域 and "New quote" button. 每个点击选取 random quote 从构建-in 数组 and shows 它 on page.
学习目标
- 存储数据 in 数组的 字符串
- Generate random 索引使用 Math.random and Math.floor
- 更新 DOM 文本从 事件处理函数
- Avoid repeating 相同 quote 两次 in 行
前置要求
- 数组 and 索引 access
- 函数
- DOM selection and 事件监听器
步骤
- 1
存储 quotes
创建数组的 at 最少 five 短 quotes. Keeping 数据 separate 从 logic 制作它 简单到 添加更多 later.
代码const quotes = [ "Stay curious.", "Small steps every day.", "Done is better than perfect.", "Read the error message.", "Make it work, then make it good.", ];预期结果
数组的 five 字符串是 ready in memory.
- 2
选取 random quote
编写函数
randomQuote()那个返回 random 元素. Math.random() gives 数字 in [0,1); multiply 通过数组长度 and floor 它到 获取有效索引.代码function randomQuote() { const i = Math.floor(Math.random() * quotes.length); return quotes[i]; }预期结果
Calling randomQuote() 返回 one 的 five 字符串, 不同每个时间.
提示
Math.floor rounds 下, 所以索引是 总是之间 0 and 长度-1 — 从不 out 的边界.
- 3
Wire button
选择 quote 元素 and button. On 点击, call randomQuote() and 设置元素's textContent. 这个连接数据到 UI.
代码const quoteEl = document.getElementById("quote"); const btn = document.getElementById("new-quote"); btn.addEventListener("click", () => { quoteEl.textContent = randomQuote(); });预期结果
每个点击 shows 新 random quote on page.
- 4
Avoid repeating 相同 quote
Keep track 的 current quote and, 如果新 one matches, 选取再次. 这个小 循环 guarantees 用户总是 sees 更改当 它们点击.
代码let current = ""; btn.addEventListener("click", () => { let next = randomQuote(); while (next === current) { next = randomQuote(); } current = next; quoteEl.textContent = next; });预期结果
点击从不 shows 相同 quote 两次 in 行.
- 5
添加输入验证与错误处理
在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 try/catch 或条件判断给出友好提示。健壮的 JS 程序不会因意外输入而崩溃。
代码function safeParse(value) { if (value === null || value === undefined || value === "") { throw new Error("Input is empty"); } const num = Number(value); if (Number.isNaN(num)) { throw new Error(`"${value}" is not a valid number`); } return num; } try { const n = safeParse(userInput); process(n); } catch (err) { console.error(err.message); }预期结果
空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。
自己动手试试
<blockquote id="quote">Click the button to get a quote!</blockquote>
<button id="new-quote">New Quote</button>
<script>
const quotes = [
/* TODO: add 5 quotes */
];
function randomQuote() {
// TODO: return a random quote
}
// TODO: wire button to show randomQuote()
</script><blockquote id="quote">Click the button to get a quote!</blockquote>
<button id="new-quote">New Quote</button>
<script>
const quotes = [
"Stay curious.",
"Small steps every day.",
"Done is better than perfect.",
"Read the error message.",
"Make it work, then make it good.",
];
function randomQuote() {
const i = Math.floor(Math.random() * quotes.length);
return quotes[i];
}
const quoteEl = document.getElementById("quote");
const btn = document.getElementById("new-quote");
let current = "";
btn.addEventListener("click", () => {
let next = randomQuote();
while (next === current) {
next = randomQuote();
}
current = next;
quoteEl.textContent = next;
});
</script>你学到了什么
你组合数组, random indexing, and DOM 事件处理函数到 构建 generator — and 添加小 guard 所以输出总是更改, 常见真实-世界 polish.
相关资源
相关练习
- 数组方法 MCQ
测验 on 数组 access and 方法.
- Math Predict
Predict result 的 Math.random and Math.floor 表达式.
相关工具
- JSON Formatter
格式 quotes 数组 as JSON 到 inspect 你的数据结构.
相关速查表
- JavaScript Cheatsheet
数组, Math, and DOM 语法引用.
相关参考文档
- JavaScript 数组方法
完整数组方法引用.
- JavaScript Math
Math 对象引用.
相关错误
- Cannot 读取属性的 undefined
undefined 元素 access.
- 引用错误不 定义
Using undefined 变量.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- Cannot 读取属性的 undefined
undefined 元素 access.
- 引用错误不 定义
Using undefined 变量.