在 Javascript 中从 Stack 弹出元素
javascriptweb developmentfront end technology
考虑 Javascript 中的简单堆栈类。
示例
class Stack {
constructor(maxSize) {
// 如果未提供,则设置默认最大大小
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // 初始化一个包含堆栈值的数组。
this.container = [];
}
// 开发此类时仅用于查看内容的方法
display() {
console.log(this.container);
}
// 检查数组是否为空
isEmpty() {
return this.container.length === 0;
}
// 检查数组是否已满
isFull() {
return this.container.length >= maxSize;
}
push(element) {
// 检查堆栈是否已满
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
}
此处的 isFull 函数仅检查容器的长度是否等于或大于 maxSize 并相应地返回。isEmpty 函数检查容器的大小是否为 0。Push 函数用于将新元素添加到堆栈中。
在本节中,我们将在此类中添加 POP 操作。从 Stack 中弹出元素意味着将它们从数组顶部移除。我们将容器数组的末尾作为数组的顶部,因为我们将对其执行所有操作。因此,我们可以按如下方式实现 pop 函数 −
示例
pop() {
// 检查是否为空
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
您可以使用以下方法检查此函数是否正常运行 −
示例
let s = new Stack(2); s.display(); s.pop(); s.push(20); s.push(30); s.pop(); s.display();
输出
这将给出输出 −
[] Stack Underflow! [ 20 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

