这个队列类有什么问题?Javascript
这是我的Que类,但我并不精通对象,因此获取对象的大小和元素对我来说不起作用这个队列类有什么问题?Javascript,javascript,arrays,Javascript,Arrays,这是我的Que类,但我并不精通对象,因此获取对象的大小和元素对我来说不起作用 class Queue{ // Array is used to implement a Queue constructor(){ this.items = {}; this.count = 0; } // enqueue(item) enqueue(element){ // adding element to the qu
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=[] 类队列{ //数组用于实现队列 建造师{ this.items=[];//问题已解决 此值为0.count; } //排队项目 排队元素{ //将元素添加到队列中 this.items.pushelement; 这个.count++; } //出列 出列{ //正在从队列中删除元素 //调用时返回下溢 //关于空队列 如果这个是空的 回流底流; 这个。计数-; 返回此.items.shift; } //正面 正面{ //返回的前元素 //在不删除队列的情况下删除该队列。 如果这个是空的 不返回队列中的元素; 返回此项。项[0]; } //空空如也 空空如也{ //如果队列为空,则返回true。 返回this.items.length==0; } //偷看 偷看{ 返回此.items[此.count] } 大小元素{ 返回这个.count; } 展示{ var结果=; var i=此。计数-1; fori;i>=0;i-{ 结果+=此。项[i]+''; } 返回结果; } } 设q=新队列; console.logq.isEmpty console.logq.size
console.logq.show 首先,你是在威胁物品,比如它是一个数组,但是你将它声明为任何类型的对象。 第二,当您调用size函数时,返回items.length可能是更好的方法。 最后,您现在可以从每个用法中删除count变量 祝你好运 您是否意识到items不是数组?