当前位置:首页 > JavaScript

js 实现恢复

2026-04-05 16:10:53JavaScript

JavaScript 实现恢复功能

撤销与恢复的基本原理

撤销和恢复功能通常基于命令模式或状态快照实现。命令模式记录操作历史,状态快照保存应用状态的副本。

命令模式示例:

class Command {
  constructor(execute, undo) {
    this.execute = execute;
    this.undo = undo;
  }
}

状态快照示例:

const history = [];
let currentState = 0;

实现撤销/恢复栈

维护两个栈结构分别存储撤销和恢复的操作:

js 实现恢复

const undoStack = [];
const redoStack = [];

function executeCommand(command) {
  command.execute();
  undoStack.push(command);
  redoStack.length = 0; // 清空重做栈
}

撤销操作实现

function undo() {
  if (undoStack.length === 0) return;

  const command = undoStack.pop();
  command.undo();
  redoStack.push(command);
}

恢复操作实现

function redo() {
  if (redoStack.length === 0) return;

  const command = redoStack.pop();
  command.execute();
  undoStack.push(command);
}

完整示例代码

class TextEditor {
  constructor() {
    this.text = '';
    this.undoStack = [];
    this.redoStack = [];
  }

  insert(str) {
    const prevText = this.text;
    this.text += str;

    this.undoStack.push({
      execute: () => this.text = prevText,
      undo: () => this.text = prevText + str
    });

    this.redoStack.length = 0;
  }

  undo() {
    if (this.undoStack.length === 0) return;

    const action = this.undoStack.pop();
    action.execute();
    this.redoStack.push(action);
  }

  redo() {
    if (this.redoStack.length === 0) return;

    const action = this.redoStack.pop();
    action.undo();
    this.undoStack.push(action);
  }
}

优化建议

  1. 限制历史记录数量防止内存问题
  2. 使用不可变数据结构提升性能
  3. 考虑使用专业库如Redux-undo

实际应用场景

  1. 文本编辑器
  2. 绘图应用
  3. 电子表格
  4. 任何需要修改历史记录的应用

注意事项

  1. 确保操作是幂等的
  2. 处理并发操作的情况
  3. 考虑操作合并的可能性
  4. 注意内存使用情况

标签: js
分享给朋友:

相关文章

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现菜单

js实现菜单

实现基本HTML结构 使用HTML创建菜单的基本框架,通常包含<ul>和<li>元素。示例结构如下: <ul id="menu"> <li><…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…

js实现原理

js实现原理

JavaScript 实现原理 JavaScript 是一种解释型语言,其实现原理涉及多个核心组件和运行机制,包括引擎、运行时环境、事件循环等。 引擎与解释执行 现代 JavaScript 引擎(如…

js 实现拖拽

js 实现拖拽

实现拖拽的基本步骤 在JavaScript中实现拖拽功能需要监听几个关键事件:mousedown、mousemove和mouseup。以下是实现的基本逻辑。 监听目标元素的mousedown事件,记…

js实现左右滑动

js实现左右滑动

实现左右滑动的 JavaScript 方法 监听触摸事件 通过 touchstart、touchmove 和 touchend 事件来检测用户的手势操作。记录触摸的起始位置和移动距离,判断滑动方向。…