以下为ChatGPT自动生成的解答,正确与否请自行判断。
BFE.devAI解答 - JavaScript 代码题
59. 实现browser history
class BrowserHistory {
constructor() {
this.history = [];
this.current = -1;
}
// 前进
forward() {
if (this.current < this.history.length - 1) {
return this.history[++this.current];
}
return null;
}
// 回退
goBack() {
if (this.current > 0) {
return this.history[--this.current];
}
return null;
}
// 访问新的url
visit(url) {
// 当前指针右侧的记录全部弹出
this.history.splice(this.current + 1);
// 新增记录
this.history.push(url);
this.current++;
}
}
思路分析:
- 使用数组
history
来存储历史记录,使用指针current
来指向当前访问的记录。 goBack()
方法通过将指针current
向左移动一个位置来实现回退,同时返回当前指向的记录。forward()
方法通过将指针current
向右移动一个位置来实现前进,同时返回当前指向的记录。visit(url)
方法用于访问新的URL,当访问新的URL时,需要将当前指针指向的记录右侧的所有记录弹出,然后将新的URL添加到数组history
的末尾,并将指针current
移到新的记录上。