Skip to content

Bar Chart 数据 Visualization

中等 约 25 分钟

你将构建什么

page 那个 takes 数组的 数据 (e.g., monthly sales) and 渲染 bar chart using div 元素. 每个 bar's 高度 represents 数据值, 使用 labels below.

学习目标

  • 渲染数据 as visual bars using DOM 元素
  • Calculate bar 高度相对到 最大值值
  • 添加 labels and 值到 每个 bar
  • Dynamically 创建 and 样式元素从 JavaScript

前置要求

  • 数组 and 数组方法 (映射, 最大值)
  • DOM creation (createElement, appendChild)
  • CSS 样式通过样式对象

步骤

  1. 1

    定义数据 and HTML 容器

    创建数组的 数据对象使用 label and 值属性. 添加容器 div for chart.

    代码
    <div id="chart" style="display:flex;align-items:flex-end;gap:10px;height:300px;"></div>
    
    <script>
      const data = [
        { label: "Jan", value: 45 },
        { label: "Feb", value: 78 },
        { label: "Mar", value: 32 },
        { label: "Apr", value: 91 },
        { label: "May", value: 60 },
      ];
    </script>

    预期结果

    空 chart 容器 appears.

  2. 2

    Calculate scale and 渲染 bars

    查找最大值值, 然后 for 每个数据点 创建 bar div 谁的高度是 proportional 到值. 添加 label below 每个 bar.

    代码
    const chart = document.getElementById("chart");
    const maxVal = Math.max(...data.map(d => d.value));
    
    data.forEach(d => {
      const bar = document.createElement("div");
      const heightPx = (d.value / maxVal) * 280; // 280px max height
      bar.style.cssText = `width:60px;height:${heightPx}px;background:#3b82f6;display:flex;align-items:flex-end;justify-content:center;color:white;`;
      bar.textContent = d.value;
      const col = document.createElement("div");
      col.style.cssText = "display:flex;flex-direction:column;align-items:center;";
      col.appendChild(bar);
      const label = document.createElement("span");
      label.textContent = d.label;
      col.appendChild(label);
      chart.appendChild(col);
    });

    预期结果

    bar chart appears 使用 5 bars 的 varying 高度 and labels.

  3. 3

    添加输入验证与错误处理

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

    预期结果

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

  4. 4

    添加事件监听与交互

    为页面元素绑定事件监听器(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();
    });

    预期结果

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

  5. 5

    测试与控制台验证

    用 console.assert 或简单断言验证核心函数的输出;在浏览器控制台运行测试,确认所有用例通过。手动验证是快速确认正确性的有效手段。

    代码
    // Run in browser console
    console.assert(coreFunc(10) === expected1, "case 1");
    console.assert(coreFunc(0) === expected2, "edge: zero");
    console.assert(coreFunc(-5) === expected3, "negative input");
    console.log("All assertions passed ✓");

    预期结果

    控制台输出 'All assertions passed ✓',无断言失败。

自己动手试试

你学到了什么

你 rendered 数据 visually 通过 dynamically 创建 DOM 元素, calculating proportional 大小, and applying CSS 样式从 JavaScript — 基础的 数据 visualization 不使用外部库.

相关资源

相关课程

  • 数组

    映射 and Math.最大值 for 数据处理.

  • DOM

    createElement and appendChild for 渲染.

相关练习

相关速查表

相关术语

相关术语

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

解读错误信息

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

查看错误

← 返回主题