答案:通过维护历史快照数组和当前指针实现撤销重做,支持最大步数限制与深拷贝状态存储。

实现一个支持撤销和重做功能的状态管理器,核心思路是记录每次状态变化的历史,并通过指针管理当前所处的历史位置。JavaScript 可以轻松实现这一机制,无需依赖外部库。
基本设计思路
状态管理器需要维护:
- 一个历史快照数组(保存所有状态)
- 一个当前状态的指针(指示当前在历史中的位置)
- 最大历史步数限制(可选,防止内存溢出)
每次更新状态时,将新状态存入历史,并移动指针;撤销时指针前移,重做时指针后移。
立即学习“Java免费学习笔记(深入)”;
实现可撤销的状态管理器类
以下是一个简洁、实用的 JavaScript 类实现:
class UndoRedoManager {
constructor(maxSteps = 50) {
this.history = [];
this.currentIndex = -1;
this.maxSteps = maxSteps;
}
setState(newState) {
// 截断当前点之后的历史(处理重做后的新操作)
this.history = this.history.slice(0, this.currentIndex + 1);
// 添加新状态
this.history.push(JSON.parse(JSON.stringify(newState)));
// 更新指针
this.currentIndex++;
// 超出最大步数时,删除最老的记录
if (this.history.length > this.maxSteps) {
this.history.shift();
this.currentIndex--;
}
}
undo() {
if (this.canUndo()) {
this.currentIndex--;
return JSON.parse(JSON.stringify(this.history[this.currentIndex]));
}
return null;
}
redo() {
if (this.canRedo()) {
this.currentIndex++;
return JSON.parse(JSON.stringify(this.history[this.currentIndex]));
}
return null;
}
canUndo() {
return this.currentIndex > 0;
}
canRedo() {
return this.currentIndex
}
getCurrentState() {
if (this.currentIndex === -1) return null;
return JSON.parse(JSON.stringify(this.history[this.currentIndex]));
}
}
使用示例
假设你在开发一个简单的文本编辑器或表单状态管理:
const manager = new UndoRedoManager(10);
manager.setState({ text: "Hello" });
manager.setState({ text: "Hello World" });
manager.setState({ text: "Hello Everyone" });
console.log(manager.undo()); // { text: "Hello World" }
console.log(manager.undo()); // { text: "Hello" }
console.log(manager.redo()); // { text: "Hello World" }
注意:使用 JSON.parse(JSON.stringify()) 实现深拷贝适用于纯数据对象。若状态包含函数、undefined、Symbol 或循环引用,需改用更健壮的深拷贝方法。
优化建议
- 对大型状态对象,考虑只存储“变更差量”而非完整快照,节省内存
- 监听状态变化并触发 UI 更新(如结合事件机制或观察者模式)
- 在 setState 前比较前后状态,避免无意义的历史记录
- 提供 clear() 方法重置历史
基本上就这些。这个模式简单有效,适合集成到表单、画布编辑、配置工具等需要操作回退的场景。










