考虑一下Javascript中的一个简单堆栈类。
class Stack {
constructor(maxSize) {
//设置默认的最大大小(如果未提供)
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
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("堆栈溢出!");
return;
}
this.container.push(element);
}
pop() {
//检查是否为空
if (this.isEmpty()) {
console.log("堆栈下溢!");
return;
}
this.container.pop();
}
peek() {
if (isEmpty()) {
console.log("堆栈下溢!");
return;
}
return this.container[this.container.length - 1];
}
}在这里,isFull函数仅检查容器的长度是否等于或大于maxSize并相应地返回。isEmpty功能检查是否尺寸容器的是0。PUSH和POP功能用于从堆栈分别添加和删除新的元素。
在本节中,我们将在此类中添加CLEAR操作。我们可以通过将容器元素重新分配为一个空数组来清除内容。例如,
clear() {
this.container = [];
}您可以使用以下命令检查此功能是否工作正常:
let s = new Stack(2); s.push(10); s.push(20); s.display(); s.clear(); s.display();
输出结果
这将给出输出-
[10, 20] []