// 基于数组封装一个优先级队列 function PriorityQueue(){ this.items = []; // 创建一个内部类,用于存放元素的内容和优先级 function QueueElement(element,priority){ this.element = element; this.priority = priority; } // 插入方法 PriorityQueue.prototype.entryQueue = function(ele,pri){ let element = new QueueElement(ele,pri); if(!this.items.length){ return this.items.push(element) } let isAdd = false; // 用于判断是否在优先级比较当中插入了 for(let i = 0; i < this.items.length; i++){ if(element.priority < this.items[i].priority){ this.items.splice(i,0,element); isAdd = true; break } } if(!isAdd){ return this.items.push(element) } } // 数据出队列 PriorityQueue.prototype.outQueue = function () { return this.items.shift() } // 查看队列的第一个数据信息 PriorityQueue.prototype.front = function () { return this.items[0] } // 判断队列是否为空 PriorityQueue.prototype.isEmpty = function () { return this.items.length == 0 } // 队列的长度 PriorityQueue.prototype.size = function () { return this.items.length } // toString PriorityQueue.prototype.toString = function () { let str = ''; for (let i = 0; i < this.items.length; i++) { str += this.items[i].element + '-' + this.items[i].priority + ' ' } return str } } let pq = new PriorityQueue(); pq.entryQueue('一般顾客',1000) pq.entryQueue('二级顾客',500) pq.entryQueue('vip顾客',100) pq.entryQueue('svip顾客',10) console.log(pq); console.log(pq.toString()); // svip顾客-10 vip顾客-100 二级顾客-500 一般顾客-1000