在 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.