簡體   English   中英

在 javascript 中創建隊列的最佳方法是什么?

[英]What is the best way to create a queue in javascript?

我知道 javascript 有 push/shift/pop 屬性可以幫助創建這種類型的數據結構。 但我明白在巨量數據上使用它們並不是一個好主意,因為它必須遍歷整個數組才能執行操作。 那么.. 一個高效代碼的例子會是什么樣子?

這是我的代碼,但是在刪除元素時使用“dequeue”時,即使它的值為“null”,它仍然存儲在內存中,我該如何避免這種情況?

class Queue {
  constructor() {
    this.items = {},
      this.front = 0,
      this.end = 0;
  }

  enqueue(data) {
    this.items[this.end] = data;
    this.end++;
  }

  dequeue() {
    if (this.front === this.end) {
      return null;
    }
    const data = this.item[this.front];
    this.front++;
    return data;
  }

  getSize() {
    return this.end - this.front;
  }
}

這是隊列數據結構的一個很好的實現,可以解決您的問題。

class Queue {

  constructor() {
    this.first = 0;
    this.last = 0;
    this.storage = {};
  }

  enqueue(value) {
    this.storage[this.last] = value;
    this.last++;
  }

  dequeue() {
    if (this.last > this.first) {
      var value = this.storage[this.first];
      this.first++;
      return value;
    } else {
      return 0;
    }
  }

  size() {
    return this.last - this.first;
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM