本文實例講述了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());//bbconsole.log(q.back());//cc
可得如下運行結果:
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答