一個用JS數組實現的隊列
/*一個用數組實現的隊列*/ 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