Skip to content

简单 Calculator

简单 约 25 分钟

你将构建什么

calculator page 使用 display 区域 and buttons for digits 0-9, 操作 (+, −, ×, ÷), equals, and 清晰. 点击 buttons 构建表达式 and shows result.

学习目标

  • 构建 calculator UI 使用 buttons
  • Handle digit and 运算符 button 点击
  • Evaluate 表达式 and display result
  • 清晰 and reset calculator 状态

前置要求

  • 函数 and conditionals
  • DOM selection and 事件监听器
  • 字符串 concatenation

步骤

  1. 1

    创建 HTML 结构

    创建 display div and buttons for digits 0-9, four 运算符, equals, and 清晰. Use 数据 attributes 到 mark 每个 button's role.

    代码
    <div id="display">0</div>
    <button data-value="7">7</button>
    <button data-value="8">8</button>
    <button data-value="+">+</button>
    <button data-value="=">=</button>
    <button data-action="clear">C</button>

    预期结果

    display showing 0 and calculator buttons appear.

  2. 2

    设置状态 and 选择元素

    Declare current 字符串到 持有表达式. 选择 display and 所有 buttons. display 总是 reflects current.

    代码
    let current = "0";
    const display = document.getElementById("display");
    const buttons = document.querySelectorAll("button");

    预期结果

    状态是 ready; display shows 0.

  3. 3

    Handle button 点击

    添加点击监听器到 每个 button. 如果它 是清晰 button, reset 到 '0'. 如果它 是 equals, evaluate 表达式. 否则, append 值到 current 表达式.

    代码
    buttons.forEach(btn => {
      btn.addEventListener("click", () => {
        const action = btn.dataset.action;
        const value = btn.dataset.value;
        if (action === "clear") {
          current = "0";
        } else if (value === "=") {
          try { current = String(eval(current)); } catch { current = "Error"; }
        } else {
          current = current === "0" ? value : current + value;
        }
        display.textContent = current;
      });
    });

    预期结果

    点击 buttons 构建 and evaluates 表达式.

  4. 4

    添加输入验证与错误处理

    在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 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);
    }

    预期结果

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

  5. 5

    添加事件监听与交互

    为页面元素绑定事件监听器(click、input、keydown 等),让程序响应用户操作。交互性是 JavaScript 在前端的核心价值。

    代码
    const button = document.querySelector("#action-btn");
    const input = document.querySelector("#user-input");
    
    button.addEventListener("click", () => {
      const value = input.value.trim();
      if (!value) return;
      runMainLogic(value);
    });
    
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") button.click();
    });

    预期结果

    点击按钮或按回车键触发主逻辑;空输入被忽略。

自己动手试试

你学到了什么

你构建工作 calculator 通过 managing 表达式状态 in 字符串, handling button 事件, and evaluating result — 核心模式后面每个 interactive calculator app.

相关资源

相关课程

  • 函数

    函数 for evaluation logic.

  • DOM

    事件 handling for button 点击.

相关练习

相关速查表

相关术语

相关术语

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

解读错误信息

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

查看错误

← 返回主题