0
点赞
收藏
分享

微信扫一扫

JavaScript队列(基于数组)


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


举报

相关推荐

0 条评论