创建一个基本的队列结构,并拥有自己的方法代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>队列</title>
</head>
<body>
<script type="text/javascript">
function Queue() {
//初始化
this.item = []
//添加
Queue.prototype.enqueue = element => {
this.item.push(element)
}
//删除
Queue.prototype.dequeue = () => this.item.shift()
//查看顶端元素
Queue.prototype.front = () => this.item[0]
//是否为空
Queue.prototype.isEmpty = () => this.item.length === 0
//长度
Queue.prototype.size = () => this.item.length
//转为string
Queue.prototype.tostring = () => {
let res = ''
for(let i in this.item) {
res += this.item[i] + ' '
}
return res
}
}
let queue = new Queue()
queue.enqueue(5)
queue.enqueue(8)
queue.enqueue(12)
queue.enqueue(19)
queue.enqueue(28)
queue.enqueue(20)
queue.enqueue(15)
queue.enqueue(22)
queue.enqueue(3)
console.log(queue)
</script>
</body>
</html>
浏览器输出如下: