帮我写个完整的js小程序端写入、存储、读取队列的代码
时间: 2023-08-07 12:03:59 浏览: 58
好的,以下是一个基于 JavaScript 的队列操作小程序:
```javascript
// 封装一个队列类
class Queue {
constructor() {
this.items = [];
}
// 判断队列是否为空
isEmpty() {
return this.items.length === 0;
}
// 向队列末尾添加元素
enqueue(item) {
this.items.push(item);
}
// 移除队列开头的元素
dequeue() {
if (this.isEmpty()) {
return null;
} else {
return this.items.shift();
}
}
// 返回队列的长度
size() {
return this.items.length;
}
}
// 实例化一个队列对象
const queue = new Queue();
// 向队列中添加元素
queue.enqueue("第一个元素");
queue.enqueue("第二个元素");
queue.enqueue("第三个元素");
// 从队列中读取元素
while (!queue.isEmpty()) {
console.log(queue.dequeue());
}
// 将队列数据存储到本地存储中
localStorage.setItem("queue", JSON.stringify(queue.items));
// 从本地存储中读取队列数据
const storedQueue = localStorage.getItem("queue");
if (storedQueue) {
queue.items = JSON.parse(storedQueue);
}
// 打印读取后的队列
console.log("读取后的队列:", queue.items);
```
以上代码实现了一个基本的队列类,通过 `enqueue` 方法向队列中写入数据,通过 `dequeue` 方法从队列中读取数据。同时,还演示了如何将队列数据存储到本地存储中,并从本地存储中读取队列数据。需要注意的是,本地存储中只能存储字符串类型的数据,因此需要使用 `JSON.stringify` 和 `JSON.parse` 方法来转换队列数据。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)