在 Javascript 中清除堆栈的元素


考虑一个 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]
[]

更新于:15-Jun-2020

765 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始使用
广告
© . All rights reserved.