Skip to content

JavaScript 综合实例

前面的篇章讲知识点,这篇把知识点拼成能直接抄走的小项目。每个实例都是"完整可运行 + 最少依赖"的标准写法,并标注了容易踩的坑。代码基于现代浏览器(ES2022),可直接放进 <script type="module"> 或构建工具项目。

第一部分:对象操作实例

实例 1:安全深拷贝

js
// 需求:复制一份嵌套对象,改副本不影响原件
function deepClone(value, seen = new WeakMap()) {
  // 原始值直接返回
  if (value === null || typeof value !== 'object') return value;

  // 循环引用:见过就直接返回上次的结果
  if (seen.has(value)) return seen.get(value);

  // Date
  if (value instanceof Date) return new Date(value.getTime());

  // 数组
  if (Array.isArray(value)) {
    const copy = [];
    seen.set(value, copy);
    value.forEach((item, i) => { copy[i] = deepClone(item, seen); });
    return copy;
  }

  // Map / Set
  if (value instanceof Map) {
    const copy = new Map();
    seen.set(value, copy);
    value.forEach((v, k) => copy.set(deepClone(k, seen), deepClone(v, seen)));
    return copy;
  }
  if (value instanceof Set) {
    const copy = new Set();
    seen.set(value, copy);
    value.forEach(v => copy.add(deepClone(v, seen)));
    return copy;
  }

  // 普通对象:保留原型
  const copy = Object.create(Object.getPrototypeOf(value));
  seen.set(value, copy);
  for (const key of Reflect.ownKeys(value)) {
    copy[key] = deepClone(value[key], seen);
  }
  return copy;
}

const original = { a: 1, nested: { b: [1, 2, { c: 3 }] } };
original.self = original;                 // 循环引用
const copy = deepClone(original);
copy.nested.b[2].c = 99;
original.nested.b[2].c;                    // 3——原件没被污染

现代偷懒法:structuredClone(original) 一行搞定(Chrome 98+ / Safari 15.4+),支持循环引用和 Date/Map/Set,不支持函数和 DOM 节点。上面手写版的价值在于理解过程和兼容老环境。

实例 2:数组按字段分组 + 统计

js
const orders = [
  { id: 1, status: 'paid', amount: 100 },
  { id: 2, status: 'unpaid', amount: 50 },
  { id: 3, status: 'paid', amount: 200 },
  { id: 4, status: 'refund', amount: 100 },
];

function groupAndSum(list, key) {
  return list.reduce((acc, item) => {
    const k = item[key];
    if (!acc[k]) acc[k] = { count: 0, total: 0 };
    acc[k].count += 1;
    acc[k].total += item.amount;
    return acc;
  }, {});
}

const stats = groupAndSum(orders, 'status');
// { paid: { count: 2, total: 300 }, unpaid: { count: 1, total: 50 }, refund: { count: 1, total: 100 } }

// 金额显示:分转元
const yuan = cents => (cents / 100).toFixed(2);
stats.paid.total;      // 300(分)→ yuan(300) === '3.00'

坑:浮点累加金额会丢精度(0.1 + 0.2),示例里 amount 用"分"存整数,只在展示时除 100。

实例 3:树形数据操作

js
// 需求:部门树查路径、找节点、统计人数
const org = {
  id: 'root', name: '总部', count: 0,
  children: [
    { id: 'tech', name: '技术部', count: 10, children: [
      { id: 'fe', name: '前端组', count: 4 },
      { id: 'be', name: '后端组', count: 6 },
    ]},
    { id: 'hr', name: '人事部', count: 2 },
  ],
};

// 找节点路径
function findPath(tree, id, path = []) {
  if (tree.id === id) return [...path, tree.name];
  if (!tree.children) return null;
  for (const child of tree.children) {
    const found = findPath(child, id, [...path, tree.name]);
    if (found) return found;
  }
  return null;
}
findPath(org, 'fe');        // ['总部', '技术部', '前端组']

// 汇总人数(后序遍历)
function sumCount(node) {
  if (!node.children?.length) return node.count;
  return node.children.reduce((sum, c) => sum + sumCount(c), 0);
}
sumCount(org);              // 12

// 广度优先转扁平(渲染面包屑/搜索用)
function flattenTree(tree) {
  const result = [];
  const queue = [tree];
  while (queue.length) {
    const node = queue.shift();
    const { children, ...rest } = node;
    result.push(rest);
    if (children) queue.push(...children);
  }
  return result;
}
flattenTree(org);           // 4 个不带 children 的节点

第二部分:浏览器对象实例

实例 4:URL 与页面状态同步

js
// 需求:列表页的筛选条件同步到 URL——刷新不丢、可分享、前进后退可用
const state = { keyword: '', category: 'all', page: 1 };

function syncToUrl() {
  const url = new URL(location.href);
  // 空值不写进 URL,保持链接干净
  Object.entries(state).forEach(([k, v]) => {
    if (v === '' || v === 'all' || v === 1) url.searchParams.delete(k);
    else url.searchParams.set(k, v);
  });
  history.pushState(state, '', url);
  render();
}

function syncFromUrl() {
  const params = new URLSearchParams(location.search);
  state.keyword = params.get('keyword') ?? '';
  state.category = params.get('category') ?? 'all';
  state.page = +(params.get('page') ?? 1);
  render();
}

// 筛选控件
categorySelect.addEventListener('change', () => {
  state.category = categorySelect.value;
  state.page = 1;                    // 改筛选回到第一页——常见遗漏
  syncToUrl();
});

window.addEventListener('popstate', syncFromUrl);
syncFromUrl();                        // 首屏从 URL 恢复

坑:pushState 不触发 popstate(改了地址要自己 render);刷新时 event.state 不保证有,从 URL 解析才是唯一可靠来源。

实例 5:复制到剪贴板(带降级)

js
// 需求:点击复制邀请码,成功给反馈
async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);    // 需 https + 通常需用户手势
    return true;
  } catch {
    // 降级:老浏览器用 textarea + execCommand
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.style.position = 'fixed';
    ta.style.opacity = '0';
    document.body.appendChild(ta);
    ta.select();
    const ok = document.execCommand('copy');
    ta.remove();
    return ok;
  }
}

copyBtn.addEventListener('click', async () => {
  const ok = await copyText(inviteCode);
  showToast(ok ? '已复制' : '复制失败,请手动复制');
});

坑:iOS Safari 对 navigator.clipboard 支持较晚,execCommand('copy') 的 textarea 必须先插入 DOM 再 select,且不能 display: none(iOS 上选不中)。

实例 6:屏幕信息与主题跟随

js
// 需求:跟随系统深浅色 + 记住用户手动选择
const STORAGE_KEY = 'theme';

function applyTheme(theme) {
  document.documentElement.dataset.theme = theme;    // CSS: [data-theme=dark] {...}
}

// 初始:本地选择优先,否则跟随系统
const saved = localStorage.getItem(STORAGE_KEY);
const systemDark = matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(saved ?? (systemDark ? 'dark' : 'light'));

// 系统主题变化时,用户没手动选过才跟着变
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
  if (!localStorage.getItem(STORAGE_KEY)) {
    applyTheme(e.matches ? 'dark' : 'light');
  }
});

// 手动切换
themeToggle.addEventListener('click', () => {
  const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
  localStorage.setItem(STORAGE_KEY, next);
  applyTheme(next);
});

坑:localStorage 的读取要 try/catch(隐私模式抛异常);首屏主题要写在 <head> 的内联 script 里,否则刷新时闪一下白屏(FOUC)。

第三部分:HTML DOM 实例

实例 7:Tab 切换(无依赖)

html
<div class="tabs">
  <div class="tab-nav">
    <button class="tab-btn active" data-target="panel-1">选项一</button>
    <button class="tab-btn" data-target="panel-2">选项二</button>
  </div>
  <div class="tab-panels">
    <div id="panel-1" class="tab-panel active">内容一</div>
    <div id="panel-2" class="tab-panel">内容二</div>
  </div>
</div>
js
function initTabs(root) {
  const btns = root.querySelectorAll('.tab-btn');
  const panels = root.querySelectorAll('.tab-panel');

  // 事件委托:一个监听器管所有 tab,未来加按钮自动生效
  root.querySelector('.tab-nav').addEventListener('click', e => {
    const btn = e.target.closest('.tab-btn');
    if (!btn) return;

    btns.forEach(b => b.classList.toggle('active', b === btn));
    const target = root.querySelector(`#${btn.dataset.target}`);
    panels.forEach(p => p.classList.toggle('active', p === target));
  });
}
initTabs(document.querySelector('.tabs'));
css
.tab-panel { display: none; }
.tab-panel.active { display: block; }

无障碍加分项:给按钮加 role="tab"、aria-selected,面板加 role="tabpanel"——读屏软件能正确朗读。

实例 8:模态框(焦点管理 + 锁定滚动)

js
// 需求:打开模态框锁定背景滚动、Esc 关闭、点遮罩关闭、关闭后焦点还原
class Modal {
  constructor(el) {
    this.el = el;
    this.lastFocus = null;
  }

  open() {
    this.lastFocus = document.activeElement;      // 记住打开前的焦点
    this.el.hidden = false;
    document.body.style.overflow = 'hidden';      // 锁滚动
    this.el.querySelector('.modal-close')?.focus();

    this._onKeydown = e => {
      if (e.key === 'Escape') this.close();
      if (e.key === 'Tab') this._trapFocus(e);    // 焦点圈在框内
    };
    document.addEventListener('keydown', this._onKeydown);

    // 点遮罩关闭(点到内容不关)
    this.el.addEventListener('click', e => {
      if (e.target === this.el) this.close();
    });
  }

  close() {
    this.el.hidden = true;
    document.body.style.overflow = '';
    document.removeEventListener('keydown', this._onKeydown);
    this.lastFocus?.focus();                       // 焦点还给触发按钮
  }

  _trapFocus(e) {
    const focusable = this.el.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    if (!focusable.length) return;
    const first = focusable[0];
    const last = focusable[focusable.length - 1];
    if (e.shiftKey && document.activeElement === first) {
      last.focus();
      e.preventDefault();
    } else if (!e.shiftKey && document.activeElement === last) {
      first.focus();
      e.preventDefault();
    }
  }
}

const modal = new Modal(document.getElementById('my-modal'));
openBtn.addEventListener('click', () => modal.open());

坑:overflow: hidden 锁滚动会丢失滚动条宽度导致页面"抖动"(补偿 padding-right);hidden 属性 + CSS display:none 才能让内容不被 Tab 聚焦(只用 opacity:0 焦点会跑进去)。

实例 9:完整待办清单(增删改查 + 过滤 + 持久化)

html
<form id="todo-form">
  <input id="todo-input" placeholder="要做什么?" required>
  <button type="submit">添加</button>
</form>
<div id="todo-filters">
  <button data-filter="all" class="active">全部</button>
  <button data-filter="active">未完成</button>
  <button data-filter="done">已完成</button>
</div>
<ul id="todo-list"></ul>
<span id="todo-count"></span>
js
const STORE_KEY = 'todos';

// —— 数据层 ——
let todos = load();
let filter = 'all';

function load() {
  try {
    return JSON.parse(localStorage.getItem(STORE_KEY)) ?? [];
  } catch {
    return [];                 // 数据被改坏不崩
  }
}
function save() {
  localStorage.setItem(STORE_KEY, JSON.stringify(todos));
}

// —— 渲染层:数据 → DOM ——
const list = document.getElementById('todo-list');

function visibleTodos() {
  if (filter === 'active') return todos.filter(t => !t.done);
  if (filter === 'done') return todos.filter(t => t.done);
  return todos;
}

function render() {
  const frag = document.createDocumentFragment();

  for (const todo of visibleTodos()) {
    const li = document.createElement('li');
    li.className = 'todo-item' + (todo.done ? ' done' : '');
    li.dataset.id = todo.id;

    const cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.checked = todo.done;
    cb.className = 'toggle';

    const span = document.createElement('span');
    span.className = 'text';
    span.textContent = todo.text;              // 用户输入——textContent 防 XSS

    const del = document.createElement('button');
    del.type = 'button';
    del.className = 'delete';
    del.textContent = '删除';

    li.append(cb, span, del);
    frag.appendChild(li);
  }

  list.replaceChildren(frag);                  // 一次性替换

  const remain = todos.filter(t => !t.done).length;
  count.textContent = `${remain} 项未完成`;
}

// —— 事件层:委托 ——
list.addEventListener('click', e => {
  const li = e.target.closest('.todo-item');
  if (!li) return;
  const id = +li.dataset.id;

  if (e.target.classList.contains('toggle')) {
    const todo = todos.find(t => t.id === id);
    todo.done = e.target.checked;
    save();
    render();
  } else if (e.target.classList.contains('delete')) {
    todos = todos.filter(t => t.id !== id);
    save();
    render();
  }
});

document.getElementById('todo-form').addEventListener('submit', e => {
  e.preventDefault();
  const input = document.getElementById('todo-input');
  const text = input.value.trim();
  if (!text) return;
  todos.push({ id: Date.now(), text, done: false });
  input.value = '';
  save();
  render();
});

document.getElementById('todo-filters').addEventListener('click', e => {
  const btn = e.target.closest('button[data-filter]');
  if (!btn) return;
  filter = btn.dataset.filter;
  document.querySelectorAll('#todo-filters button').forEach(b =>
    b.classList.toggle('active', b === btn)
  );
  render();
});

render();        // 首屏从 localStorage 恢复

这个例子串起来的知识点:localStorage 持久化(try/catch 容错)、createDocumentFragment 批量插入、事件委托(checkbox 和删除共用一个监听)、textContent 防 XSS、Date.now() 当简易 ID、replaceChildren 清空重渲。

生产升级方向:ID 用 crypto.randomUUID();大量任务时分页/虚拟列表;多标签同步加 storage 事件监听。

实例 10:图片懒加载(原生优先)

html
<img src="placeholder.svg" data-src="real.jpg" alt="描述" width="400" height="300">
js
// 原生方案(现代浏览器首选,无 JS)
// <img src="real.jpg" loading="lazy" alt="描述" width="400" height="300">

// JS 方案(老浏览器兜底)
const io = new IntersectionObserver(entries => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    const img = entry.target;
    img.src = img.dataset.src;
    img.addEventListener('load', () => img.classList.add('loaded'));
    img.addEventListener('error', () => { img.src = 'error.png'; });
    io.unobserve(img);                 // 加载一次就取消观察
  }
});

document.querySelectorAll('img[data-src]').forEach(img => io.observe(img));

坑:懒加载图片必须写 width/height(或 CSS aspect-ratio),否则加载完成后布局跳动(CLS);loading="lazy" 的首屏图片别用(会拖慢 LCP)。

相关阅读

CTO Plus技术栈 Version 1.0.20261024-12