javascript - 这个队列类有什么问题?Javascript
问题描述
这是我的 Que 课程,但我并不熟悉对象,因此获取对象的大小和元素对我不起作用
class Queue{
// Array is used to implement a Queue
constructor(){
this.items = {};
this.count = 0;
}
// enqueue(item)
enqueue(element){
// adding element to the queue
this.items.push(element);
this.count++;
}
// dequeue()
dequeue(){
// removing element from the queue
// returns underflow when called
// on empty queue
if(this.isEmpty())
return "Underflow";
this.count--;
return this.items.shift();
}
// front()
front(){
// returns the Front element of
// the queue without removing it.
if(this.isEmpty())
return "No elements in Queue";
return this.items[0];
}
// 是空的()
isEmpty(){
// return true if the queue is empty.
return this.items.length == 0;
}
// peek()
peek(){
return this.items[this.count]
}
size(element){
return this.count;
}
show(){
var result = '';
var i=this.count-1;
for(i; i>=0; i--){
result += this.items[i] +' ';
}
return result;
}
}
size()、show() 和 isEmpty() 等方法不起作用?他们返回未定义。
解决方案
您的代码中的小错误。只需将对象文字更改为项目的数组文字即可。this.items = []
class Queue{
// Array is used to implement a Queue
constructor(){
this.items = []; //the problem is resolved
this.count = 0;
}
// enqueue(item)
enqueue(element){
// adding element to the queue
this.items.push(element);
this.count++;
}
// dequeue()
dequeue(){
// removing element from the queue
// returns underflow when called
// on empty queue
if(this.isEmpty())
return "Underflow";
this.count--;
return this.items.shift();
}
// front()
front(){
// returns the Front element of
// the queue without removing it.
if(this.isEmpty())
return "No elements in Queue";
return this.items[0];
}
// isEmpty()
isEmpty(){
// return true if the queue is empty.
return this.items.length == 0;
}
// peek()
peek(){
return this.items[this.count]
}
size(element){
return this.count;
}
show(){
var result = '';
var i=this.count-1;
for(i; i>=0; i--){
result += this.items[i] +' ';
}
return result;
}
}
let q = new Queue();
console.log(q.isEmpty())
console.log(q.size())
console.log(q.show());
推荐阅读
- impala - IMPALA - 如何获取范围分区大小
- javascript - 从集合中获取文档数据 - 使用 Firestore 安全规则
- r - R中的二次判别分析(QDA)图
- r - 方程函数`$`未在 R-Markdown 中注册
- javascript - 使用 javascript 将数据发送到 api 时出现 cors 问题
- pandas - Pandas - 通过从另一行查找值来更新值
- java - 从java selenium-web驱动程序最大化站点的窗口大小
- go - 通过 Golang 形成 YAML
- python - 我的函数使用克莱默方法找到我的一组线性方程的 3 个解有什么问题?
- c - 有没有办法在递归中找到数字位置?