javaScript實(shí)現(xiàn)一個隊(duì)列的方法
1.隊(duì)列是遵循先進(jìn)先出(FIFO)原則的一組有序的項(xiàng),隊(duì)列在尾部添加元素,并從頂部移除元素,最新添加的元素必須排在隊(duì)列的末尾。生活中常見的例子如排隊(duì)等。
2.創(chuàng)建一個隊(duì)列類
class Queue{
constructor(){
this.count = 0;//記錄隊(duì)列的數(shù)量
this.lowestCount = 0;//記錄當(dāng)前隊(duì)列頭部的位置
this.items = [];//用來存儲元素。
}
}
3.添加元素
enqueue(element){
this.items[this.count] = element;
this.count++;
}
4.刪除元素(只刪除隊(duì)列頭部)
dequeue(){
if(this.isEmpty()){
return 'queue is null';
}
let resulte = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return resulte;
}
5.查看隊(duì)列頭部元素
peek(){
return this.items[this.lowestCount];
}
6.判斷隊(duì)列是否為空
isEmpty(){
return this.count - this.lowestCount === 0;
}
7.清除隊(duì)列的元素
clear(){
this.count = 0;
this.lowestCount = 0;
this.items = [];
}
8.查看隊(duì)列的長度
size(){
return this.count - this.lowestCount;
}
9.查看隊(duì)列的所有內(nèi)容
toString(){
if(this.isEmpty())return "queue is null";
let objString = this.items[this.lowestCount];
for(let i = this.lowestCount+1; i < this.count;i++){
objString = `${objString},${this.items[i]}`;
}
return objString;
}
10.完整代碼
class Queue{
constructor(){
this.count = 0;//記錄隊(duì)列的數(shù)量
this.lowestCount = 0;//記錄當(dāng)前隊(duì)列頂部的位置
this.items = [];//用來存儲元素。
}
enqueue(element){
this.items[this.count] = element;
this.count++;
}
dequeue(){
if(this.isEmpty()){
return 'queue is null';
}
let resulte = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return resulte;
}
peek(){
return this.items[this.lowestCount];
}
isEmpty(){
return this.count - this.lowestCount === 0;
}
size(){
return this.count - this.lowestCount;
}
clear(){
this.count = 0;
this.lowestCount = 0;
this.items = [];
}
toString(){
if(this.isEmpty())return "queue is null";
let objString = this.items[this.lowestCount];
for(let i = this.lowestCount+1; i < this.count;i++){
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}
11.運(yùn)行結(jié)果

以上就是javaScript實(shí)現(xiàn)一個隊(duì)列的方法的詳細(xì)內(nèi)容,更多關(guān)于javaScript實(shí)現(xiàn)一個隊(duì)列的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript中Object基礎(chǔ)內(nèi)部方法圖
本篇文章通過一張?jiān)敿?xì)的JavaScript中Object基礎(chǔ)內(nèi)部方法圖介紹了其基本用法,需要的朋友參考下。2018-02-02
快速理解 JavaScript 中的 LHS 和 RHS 查詢的用法
本篇文章主要介紹了快速理解 JavaScript 中的 LHS 和 RHS 查詢的用法,有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
用window.onerror捕獲并上報(bào)Js錯誤的方法
這篇文章主要介紹了用window.onerror捕獲并上報(bào)Js錯誤的方法,需要的朋友可以參考下2016-01-01
js獲取html的span標(biāo)簽的值方法(超簡單)
下面小編就為大家?guī)硪黄猨s獲取html的span標(biāo)簽的值方法(超簡單)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07
當(dāng)鼠標(biāo)移出灰色區(qū)域時候,菜單項(xiàng)怎么隱藏起來
當(dāng)鼠標(biāo)移出灰色區(qū)域時候,菜單項(xiàng)怎么隱藏起來...2007-11-11

