今天就跟大家聊聊有關怎么在JavaScript中使用數組實現一個隊列功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
具體如下:
/*一個用數組實現的隊列*/ function Queue(){ this.dataStore = [];//存放隊列的數組,初始化為空 this.enqueue = enqueue;//向隊列尾部添加一個元素 this.dequeue = dequeue;//刪除隊首的元素 this.theFront = theFront;//讀取隊首的元素 this.back = back;//對取隊尾的元素 this.toStrings = toStrings;//顯示隊列內的所有元素 this.empty = empty;//判斷隊列是否為空 } function enqueue(element){ this.dataStore.push(element); } function dequeue(){ this.dataStore.shift(); } function theFront(){ return this.dataStore[0]; } function back(){ return this.dataStore[this.dataStore.length-1]; } function toStrings(){ return this.dataStore; } function empty(){ if(this.dataStore.length == 0){ return true; }else{ return false; } } /*測試程序*/ var q = new Queue(); q.enqueue("aa"); q.enqueue("bb"); q.enqueue("cc"); console.log(q.toStrings());//[ 'aa', 'bb', 'cc' ] q.dequeue(); console.log(q.toStrings());//[ 'bb', 'cc' ] console.log(q.theFront());//bb console.log(q.back());//cc
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼,可得如下運行結果:
看完上述內容,你們對怎么在JavaScript中使用數組實現一個隊列功能有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。