Skip to content

Random Quote Generator

简单 约 15 分钟

你将构建什么

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. 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. 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 字符串, 不同每个时间.

  3. 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. 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. 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);
    }

    预期结果

    空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。

自己动手试试

你学到了什么

你组合数组, random indexing, and DOM 事件处理函数到 构建 generator — and 添加小 guard 所以输出总是更改, 常见真实-世界 polish.

相关资源

相关课程

  • 数组

    数组 indexing and 长度属性 used 到选取 random quote.

  • DOM

    点击监听器那个触发新 quote.

相关练习

相关工具

  • JSON Formatter

    格式 quotes 数组 as JSON 到 inspect 你的数据结构.

相关速查表

相关参考文档

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题