<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// 基于对象的队列
class Queue {
// 构造函数
constructor(){
this.count = 0; //记录最后的元素的键
this.lowstCount = 0; //追踪第一个元素的键
this.items = {};
}
// 插入数据
push(element){
this.items[this.count] = element;
this.count ++;
console.log(`插入${element}成功`); // ``结合${}打印较方便
}
// 删除数据
pop(){
if(this.isEmpty()){
console.log('对列为空,删除失败');
return undefined;
}
else
{
console.log('删除'+this.items[this.lowstCount]+'成功');
delete this.items[this.lowstCount];
this.lowstCount++ ;
}
}
// 判断是否为空
isEmpty(){
return this.size() == 0;
}
// 获取队列最前面的值
peak(){
if(this.isEmpty()){
console.log('对列为空');
return undefined;
}
return this.items[this.lowstCount];
}
// 获得对列的长度
size(){
return this.count - this.lowstCount;
}
// 清空队列
clear(){
this.items = {};
console.log(`队列清空成功`)
}
}
// 声明一个对象
const queue = new Queue();
queue.push(2);
queue.push(3);
queue.size();
queue.pop();
queue.clear();
</script>
</body>
</html>