简体   繁体   English

在 javascript 中创建队列的最佳方法是什么?

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

I know that javascript has push / shift / pop properties that help to create this type of data structure.我知道 javascript 有 push/shift/pop 属性可以帮助创建这种类型的数据结构。 But I understand that using them on giant data is not such a good idea, because it must go through the entire array to execute the action.但我明白在巨量数据上使用它们并不是一个好主意,因为它必须遍历整个数组才能执行操作。 So.. What would an example of efficient code look like?那么.. 一个高效代码的例子会是什么样子?

This is my code, but when using "dequeue" when deleting an element it is still stored in memory even though it has the value "null", how could I avoid this?这是我的代码,但是在删除元素时使用“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;
  }
}

Here's a good implementation for the Queue Data structure that will solve your problem.这是队列数据结构的一个很好的实现,可以解决您的问题。

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