在javascript中创建派生数组类型

6jjcrrmo  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(240)

我想基于js数组创建自己的javascript队列类型。我希望队列的示例是js数组的全功能示例。我希望他们有一些额外的方法,从enq(enqueue)和deq(dequeue)方法开始。我的第一次尝试失败了,原因我不明白。

function makeQueue_attempt_1() {
  let prototype = Object.create(Array.prototype);
  prototype.enq = Array.prototype.shift;
  prototype.deq = Array.prototype.pop;
  return Object.create(prototype);
}

问题1:为什么我的实现不起作用?这是一个好主意还是我想用其他方法来做?
问题2:什么是更好的方法?

f4t66c6m

f4t66c6m1#

您可以创建一个名为 Queue 或者任何你想要的。在那里,您可以实现您的功能。

class Queue {
  constructor() {
      this.value = [];
  }

  enqueue(val) {
    this.value.push(val);
    return this;
  }

  dequeue() {
    this.value.shift();
    return this;
  }

  get() {
    return this.value;
  }
}

const queue = new Queue();
queue.enqueue(20)
  .enqueue(10)
  .enqueue(22);

console.log('after enqueued:', queue.get());

queue.dequeue();
console.log('after dequeued:', queue.get());
解释

创建一个名为 Queue 内部 constructor 函数初始化 this.value 使用空数组。
创建一个 enqueue 方法,该方法将在 value 最后返回用于链接的类的示例。
创建一个 dequeue 方法,该方法将从 value 并返回 this 例如。
创建一个 get 获取队列更新值的方法。

7y4bm7vi

7y4bm7vi2#

使用数组实现javascript队列
可以使用两种数组类型的方法将数组用作队列:
使用push()方法在数组末尾添加一个元素。此方法相当于排队操作。使用shift()方法从数组的前面删除元素。这与出列操作相同。让我们通过使用数组实现javascript队列数据结构。
以下是队列的构造函数:

function Queue() {
   this.elements = [];
}

queue()构造函数使用数组存储其元素。
方法的作用是:在队列的末尾添加一个元素。我们使用数组对象的push()方法在队列的末尾插入新元素。

Queue.prototype.enqueue = function (e) {
   this.elements.push(e);
};

dequeue()方法从队列前面移除一个元素。在dequeue()方法中,我们使用数组的shift()方法删除队列前面的元素。

// remove an element from the front of the queue
Queue.prototype.dequeue = function () {
    return this.elements.shift();
};

方法通过检查数组的length属性是否为零来检查队列是否为空。

// check if the queue is empty
Queue.prototype.isEmpty = function () {
    return this.elements.length == 0;
};

peek()方法访问队列前面的元素,而不修改它。

// get the element at the front of the queue
Queue.prototype.peek = function () {
    return !this.isEmpty() ? this.elements[0] : undefined;
};

为了查询队列的长度,我们开发了length()方法:

Queue.prototype.length = function() {
    return this.elements.length;
}

要从queue()构造函数创建新队列,请使用new关键字,如下所示:

let q = new Queue();

要将数字从1排到7,请使用以下代码。

for (let i = 1; i <= 7; i++) {
    q.enqueue(i);
}

要获取队列前面的数字,可以使用peek()方法。

// get the current item at the front of the queue
console.log(q.peek()); // 1

要获取队列的当前长度,请使用以下示例中的length()方法。

// get the current length of queue
console.log(q.length()); // 7

要删除队列前面的元素,请使用dequeue()方法,如下所示:

// dequeue all elements
while (!q.isEmpty()) {
    console.log(q.dequeue());
}

//1
//2
//3
//4
//5
//6
//7

现在,您应该对队列数据结构有了很好的理解,并且知道如何使用数组类型的push()和shift()方法在javascript中实现队列。

相关问题