清除 JavaScript 中 Stack 元素
考虑 JavaScript 中的一个简单堆栈类。
示例
class Stack {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
this.container = [];
}
// A method just to see the contents while we develop this class
display() {
console.log(this.container);
}
// Checking if the array is empty
isEmpty() {
return this.container.length === 0;
}
// Check if array is full
isFull() {
return this.container.length >= maxSize;
}
push(element) {
// Check if stack is full
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
peek() {
if (isEmpty()) {
console.log("Stack Underflow!");
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] []
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP