实现 JavaScript 栈机制
什么是栈数据结构?
栈是保存元素列表的数据结构。 栈基于 LIFO
原则(先进后出)工作,这意味着最近添加的元素是第一个要删除的元素。
栈有两个仅在堆栈顶部发生的主要操作:push
和 pop
。 push 操作将一个元素放在栈顶,而 pop 操作从栈顶移除一个元素。
为了更好地理解,我们可以将栈视为一组相互堆叠的物理物品(卡片组、书籍),只有一个限制:我们只能从顶部放置或取出物品。
JavaScript 有一种机制,解释器可以跟踪它在调用多个函数的脚本中的位置——当前正在运行什么函数以及从该函数中调用了哪些函数。 它被称为
Call Stack
,它实现了所有的堆栈原则(每当我们调用一个函数时,它都会自动添加到Call Stack的顶部。一旦函数执行完所有代码,它就会自动从Call Stack
的顶部移除)
让我们实现我们自己的栈
我们将从创建我们的 Stack 类开始
class Stack {
constructor() {
this.stackItems = [];
}
}
我们的 Stack 类将具有以下方法:
- push(item) — 将一个项目添加到栈的顶部
- pop — 从栈中删除一个元素,如果在空栈上调用该函数,则表示“下溢”
- peek — 返回栈顶元素而不将其从栈中移除
- isEmpty — 检查栈是否为空
- print — 打印所有栈中的元素项
class Stack {
constructor() {
this.stackItems = [];
}
push(item) {
this.stackItems.push(item);
}
pop() {
if (this.stackItems.length === 0) {
return "Underflow";
}
return this.stackItems.pop();
}
peek() {
return this.stackItems[this.stackItems.length - 1];
}
isEmpty() {
return this.stackItems.length === 0;
}
print() {
return this.stackItems.join(', ');
}
}
将栈用于“undo”选项
我们已经实现了自己的栈。 现在我们可以将它用于诸如撤消选项之类的事情。
实现撤消方法(以及重做)的常用方法有两种:备忘录模式(Memento Pattern)和命令模式(Command Pattern)。 在本文中,我们将使用备忘录模式。
在应用操作之前,我们将当前状态的快照保存到数组中。 那个快照就是 备忘录。
如果用户想要撤消,我们只需弹出最后一个备忘录并应用它。 程序返回到应用最后一个操作之前的状态。
这种模式在效率方面是有限的。 每个备忘录都比较大,因为它捕获了整个当前状态,但它可以用于演示。
带有撤消选项的输入 React 实现
import * as React from "react";
import { Stack } from "./utils/stack";
export const BufferedInput = () => {
const [value, setValue] = React.useState("");
const snapshots = React.useRef(new Stack());
React.useEffect(() => {
snapshots.current.push(value);
}, [value]);
const handleChange = (e) => {
setValue(e.target.value);
};
const undo = () => {
const previousSnapshot = snapshots.current.pop();
setValue(previousSnapshot);
};
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<button onClick={undo}>Undo</button>
</div>
);
};
这个实现会在每个按键上生成输入值的快照,这可能不是那么有用,并且对用户体验也不是很友好,所以让我们使用 debounce
技术对其进行更新:
import * as React from "react";
import debounce from "lodash/debounce";
import { Stack } from "./utils/stack";
export const BufferedInput = () => {
const [value, setValue] = React.useState("");
const [debouncedState, setDebouncedState] = React.useState("");
const snapshots = React.useRef(new Stack());
React.useEffect(() => {
snapshots.current.push(value);
}, [debouncedState]);
const handleChange = (e) => {
setValue(e.target.value);
debouncedSnapshot(e.target.value);
};
const debouncedSnapshot = React.useCallback(
debounce((value) => {
setDebouncedState(value);
}, 500),
[]
);
const undo = () => {
setValue(snapshots.current.pop());
};
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<button onClick={undo}>Undo</button>
</div>
);
};
注意
💡 :此代码仅用于演示来说明我们的栈的实现。 我不建议在生产环境中使用它。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。