返回
打造你的个人历史记录系统,实现撤回、重做、清空等操作!
前端
2023-11-13 06:49:14
实现历史记录功能的方法有很多,今天给大家分享一种基于JavaScript的封装方案,它支持撤回、重做、清空等常见操作,适用于需要历史记录的系统中。
1. Class 版本
// 定义 History class
class History {
constructor() {
this.stack = []; // 历史记录栈
this.index = -1; // 当前操作位置
}
// 添加记录项到历史栈
add(item) {
this.stack.length = this.index + 1; // 清除未来记录
this.stack.push(item);
this.index++;
}
// 撤回
undo() {
if (this.index > 0) {
this.index--;
return this.stack[this.index];
}
return null;
}
// 重做
redo() {
if (this.index < this.stack.length - 1) {
this.index++;
return this.stack[this.index];
}
return null;
}
// 清空
clear() {
this.stack = [];
this.index = -1;
}
}
// 用法示例
const history = new History();
history.add('操作1');
history.add('操作2');
history.add('操作3');
console.log(history.undo()); // '操作3'
console.log(history.undo()); // '操作2'
console.log(history.redo()); // '操作3'
console.log(history.clear()); // []
2. 构造函数版本
// 定义 History 函数
function History() {
// 私有变量
var stack = [];
var index = -1;
// 公共方法
this.add = function(item) {
stack.length = index + 1;
stack.push(item);
index++;
};
this.undo = function() {
if (index > 0) {
index--;
return stack[index];
}
return null;
};
this.redo = function() {
if (index < stack.length - 1) {
index++;
return stack[index];
}
return null;
};
this.clear = function() {
stack = [];
index = -1;
};
}
// 用法示例
const history = new History();
history.add('操作1');
history.add('操作2');
history.add('操作3');
console.log(history.undo()); // '操作3'
console.log(history.undo()); // '操作2'
console.log(history.redo()); // '操作3'
console.log(history.clear()); // []
为了避免历史栈被外部直接修改导致出错,我们对历史栈进行了封装,仅允许通过内部方法进行操作。这样,就可以确保历史栈始终处于一致的状态,不会出现历史记录不正确的情况。
此外,我们还补充说明了如何根据用户的操作将记录项添加到历史栈中,以及如何根据用户的撤回和重做操作在历史栈中执行相应的操作。通过这种方式,可以轻松实现历史记录功能,满足不同系统的需求。