js 实现恢复
JavaScript 实现恢复功能
撤销与恢复的基本原理
撤销和恢复功能通常基于命令模式或状态快照实现。命令模式记录操作历史,状态快照保存应用状态的副本。
命令模式示例:
class Command {
constructor(execute, undo) {
this.execute = execute;
this.undo = undo;
}
}
状态快照示例:
const history = [];
let currentState = 0;
实现撤销/恢复栈
维护两个栈结构分别存储撤销和恢复的操作:

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);
}
}
优化建议
- 限制历史记录数量防止内存问题
- 使用不可变数据结构提升性能
- 考虑使用专业库如Redux-undo
实际应用场景
- 文本编辑器
- 绘图应用
- 电子表格
- 任何需要修改历史记录的应用
注意事项
- 确保操作是幂等的
- 处理并发操作的情况
- 考虑操作合并的可能性
- 注意内存使用情况






