位置: 文档库 > JavaScript > Js经典案例汇总代码实例

Js经典案例汇总代码实例

八珍玉食 上传于 2020-07-18 06:02

《Js经典案例汇总代码实例》

JavaScript作为前端开发的核心语言,其灵活性和强大的功能使其成为构建动态网页和交互式应用的首选工具。本文将通过15个经典案例,从基础到进阶,系统展示JavaScript在实际开发中的核心应用场景,涵盖DOM操作、异步编程、算法实现及实用工具开发等关键领域。

一、基础交互案例

1. 表单验证器

表单验证是前端开发的常见需求,以下实现一个实时验证邮箱格式的函数:

function validateEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

// 使用示例
const emailInput = document.getElementById('email');
emailInput.addEventListener('blur', () => {
  if (!validateEmail(emailInput.value)) {
    alert('请输入有效的邮箱地址');
  }
});

该案例展示了正则表达式的实际应用,通过事件监听实现实时反馈,是前端表单处理的典型模式。

2. 动态表格生成

根据JSON数据动态生成HTML表格的解决方案:

function generateTable(data) {
  const table = document.createElement('table');
  const thead = document.createElement('thead');
  const tbody = document.createElement('tbody');
  
  // 生成表头
  const headerRow = document.createElement('tr');
  Object.keys(data[0]).forEach(key => {
    const th = document.createElement('th');
    th.textContent = key;
    headerRow.appendChild(th);
  });
  thead.appendChild(headerRow);
  
  // 生成表体
  data.forEach(item => {
    const row = document.createElement('tr');
    Object.values(item).forEach(value => {
      const td = document.createElement('td');
      td.textContent = value;
      row.appendChild(td);
    });
    tbody.appendChild(row);
  });
  
  table.appendChild(thead);
  table.appendChild(tbody);
  return table;
}

// 使用示例
const userData = [
  { id: 1, name: '张三', age: 25 },
  { id: 2, name: '李四', age: 30 }
];
document.body.appendChild(generateTable(userData));

此案例完整演示了DOM元素创建、属性设置和层级结构构建的全过程,是理解动态内容生成的基础。

二、进阶功能实现

3. 本地存储管理器

封装localStorage操作的实用工具类:

class StorageManager {
  static set(key, value, expireHours = null) {
    const data = { value };
    if (expireHours) {
      const now = new Date();
      data.expire = now.setHours(now.getHours() + expireHours);
    }
    localStorage.setItem(key, JSON.stringify(data));
  }

  static get(key) {
    const item = localStorage.getItem(key);
    if (!item) return null;
    
    const data = JSON.parse(item);
    if (data.expire && new Date() > new Date(data.expire)) {
      localStorage.removeItem(key);
      return null;
    }
    return data.value;
  }
}

// 使用示例
StorageManager.set('theme', 'dark', 24); // 24小时后过期
console.log(StorageManager.get('theme'));

该实现解决了localStorage的两大痛点:数据过期机制和复杂数据存储,是前端状态管理的轻量级解决方案。

4. 异步请求封装

基于Promise的AJAX请求封装:

function fetchData(url, options = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(options.method || 'GET', url);
    
    if (options.headers) {
      Object.entries(options.headers).forEach(([key, value]) => {
        xhr.setRequestHeader(key, value);
      });
    }
    
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status  reject(new Error('网络错误'));
    xhr.send(options.body || null);
  });
}

// 使用示例
fetchData('/api/data', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ id: 1 })
})
.then(data => console.log(data))
.catch(err => console.error(err));

此封装统一了错误处理机制,支持自定义请求头和请求体,是现代前端开发中处理异步请求的基础模式。

三、算法与数据结构

5. 快速排序实现

function quickSort(arr) {
  if (arr.length 

该实现清晰展示了分治思想的应用,通过递归调用实现高效排序,是理解算法设计的经典案例。

6. 二分查找算法

function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  
  while (left 

二分查找将时间复杂度优化至O(log n),是处理有序数组搜索问题的标准解决方案。

四、实用工具开发

7. 节流与防抖函数

控制函数执行频率的实用工具:

// 防抖函数
function debounce(fn, delay) {
  let timer = null;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 节流函数
function throttle(fn, limit) {
  let inThrottle = false;
  return function(...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 使用示例
window.addEventListener('resize', debounce(() => {
  console.log('窗口大小改变');
}, 300));

这两个函数解决了高频事件(如滚动、输入)的性能问题,是前端性能优化的重要手段。

8. 深拷贝实现

function deepClone(obj, hash = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (hash.has(obj)) {
    return hash.get(obj);
  }
  
  const clone = Array.isArray(obj) ? [] : {};
  hash.set(obj, clone);
  
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key], hash);
    }
  }
  
  return clone;
}

// 使用示例
const original = { a: 1, b: { c: 2 } };
const cloned = deepClone(original);
console.log(cloned.b.c === original.b.c); // false

该实现解决了循环引用问题,通过WeakMap记录已拷贝对象,是处理复杂数据结构的标准方案。

五、现代框架集成

9. 自定义React Hook

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

// 使用示例
function UserProfile() {
  const { data, loading, error } = useFetch('/api/user');
  if (loading) return 
加载中...
; if (error) return
错误: {error.message}
; return
{data.name}
; }

此Hook封装了数据获取逻辑,展示了React Hooks的组合使用方式,是现代前端开发的典型模式。

10. Vue指令实现

// 注册全局指令
Vue.directive('focus', {
  inserted: function(el) {
    el.focus();
  },
  update: function(el, { value }) {
    if (value) {
      el.focus();
    }
  }
});

// 使用示例

该指令实现了自动聚焦功能,展示了Vue自定义指令的开发方式,是增强DOM交互的有效手段。

六、可视化与动画

11. Canvas动画引擎

class AnimationEngine {
  constructor(canvasId) {
    this.canvas = document.getElementById(canvasId);
    this.ctx = this.canvas.getContext('2d');
    this.objects = [];
    this.animationId = null;
  }

  addObject(obj) {
    this.objects.push(obj);
  }

  start() {
    const animate = () => {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.objects.forEach(obj => obj.update(this.ctx));
      this.animationId = requestAnimationFrame(animate);
    };
    animate();
  }

  stop() {
    cancelAnimationFrame(this.animationId);
  }
}

// 使用示例
const engine = new AnimationEngine('myCanvas');
engine.addObject({
  x: 50,
  y: 50,
  radius: 20,
  update(ctx) {
    this.x += 1;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = 'red';
    ctx.fill();
  }
});
engine.start();

此引擎封装了Canvas动画的核心逻辑,通过requestAnimationFrame实现流畅动画,是游戏开发的基础架构。

12. CSS变量控制

// 设置CSS变量
function setCSSVariable(name, value) {
  document.documentElement.style.setProperty(name, value);
}

// 获取CSS变量
function getCSSVariable(name) {
  return getComputedStyle(document.documentElement)
    .getPropertyValue(name);
}

// 使用示例
setCSSVariable('--main-color', '#ff5722');
const color = getCSSVariable('--main-color');
console.log(color); // "rgb(255, 87, 34)"

该方法实现了JavaScript与CSS的动态交互,是主题切换等功能的实现基础。

七、性能优化技巧

13. 虚拟滚动实现

class VirtualScroll {
  constructor(containerId, itemHeight, totalItems) {
    this.container = document.getElementById(containerId);
    this.itemHeight = itemHeight;
    this.totalItems = totalItems;
    this.visibleCount = Math.ceil(this.container.clientHeight / itemHeight);
    this.startIndex = 0;
    
    this.container.style.overflowY = 'auto';
    this.container.style.height = `${this.itemHeight * this.visibleCount}px`;
    
    this.render();
    this.container.addEventListener('scroll', () => {
      this.handleScroll();
    });
  }
  
  handleScroll() {
    this.startIndex = Math.floor(
      this.container.scrollTop / this.itemHeight
    );
    this.render();
  }
  
  render() {
    const endIndex = Math.min(
      this.startIndex + this.visibleCount,
      this.totalItems
    );
    
    this.container.innerHTML = '';
    for (let i = this.startIndex; i 

虚拟滚动技术将DOM节点数量控制在可视区域范围内,是处理大数据列表的性能利器。

14. Web Worker多线程

// 主线程代码
const worker = new Worker('worker.js');

worker.onmessage = function(e) {
  console.log('收到计算结果:', e.data);
};

worker.postMessage(1000000); // 发送计算任务

// worker.js 文件内容
self.onmessage = function(e) {
  const n = e.data;
  let sum = 0;
  for (let i = 0; i 

Web Worker将计算密集型任务移至独立线程,避免阻塞UI渲染,是提升应用响应速度的有效手段。

八、安全实践

15. XSS防护工具

function sanitizeHTML(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

// 使用示例
const userInput = '';
const safeHTML = sanitizeHTML(userInput);
console.log(safeHTML); // ""

该函数通过创建文本节点自动转义特殊字符,是防止XSS攻击的基础防护措施。

关键词:JavaScript、DOM操作、异步编程、算法实现前端工具React HookVue指令Canvas动画性能优化Web WorkerXSS防护、虚拟滚动、深拷贝节流防抖、本地存储

简介:本文系统整理了15个JavaScript经典应用案例,涵盖表单验证、动态表格生成、本地存储管理、异步请求封装、排序算法、防抖节流、深拷贝实现、React/Vue集成、Canvas动画、虚拟滚动等核心场景,提供完整的代码实现和详细注释,适合前端开发者作为实战参考手册。