JS队列实现 发表于 2017-06-02 | 队列即 FIFO 先进先出队列, 同样有着广泛的应用, 下面是相关的示例代码: //队列的实现 function Queue(){123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596//队列的实现function Queue(){ this.dataStore = []; this.enqueue = enqueue; this.dequeue = dequeue; this.front = front; this.back = back; this.toString = toString; this.empty = empty; this.count = count;}function count(){ return this.dataStore.length;}function enqueue(element) { this.dataStore.push(element);}function dequeue(){ return this.dataStore.shift();}function front() { return this.dataStore[0];}function back() { return this.dataStore[this.dataStore.length-1];}function toString(){ var retStr = ""; for (var i = 0; i < this.dataStore.length; i++){ retStr += this.dataStore[i] + "\n"; } return retStr;}function empty() { if( this.dataStore.length === 0){ return true; } else{ return false; }}//模拟方块舞//从txt文件中获取舞者function Dancer(name,sex){ this.name = name; this.sex = sex;}var fs = require('fs');function getDancers(males, females) { var names = fs.readFileSync("dancers.txt", "utf-8").split("\n"); for (var i = 0; i < names.length; ++i) { names[i] = names[i].trim(); } for (var i = 0; i < names.length; ++i) { var dancer = names[i].split(" "); var sex = dancer[0]; var name = dancer[1]; if (sex == "F") { females.enqueue(new Dancer(name, sex)); } else { males.enqueue(new Dancer(name, sex)); } }}//进行配对function dance(males, females) { console.log("The dance partners are: \n"); while(!females.empty() && !males.empty()) { person = females.dequeue(); console.log("Female dancer is: " + person.name); person = males.dequeue(); console.log(" and the male dancer is: " + person.name); } console.log(' ');}//方块舞测试程序function dance_test(){ var maleDancers = new Queue(); var femaleDancers = new Queue(); getDancers(maleDancers, femaleDancers); dance(maleDancers, femaleDancers); if(!femaleDancers.empty()) { console.log(femaleDancers.front().name + " is waiting to dance."); } if(!maleDancers.empty()){ console.log(maleDancers.front().name + " is waiting to dance."); }}