JavaScript 实现单链表队列:类定义、入队与出队操作详解
作者:木棉时间:2026-10-23 14:53:29浏览:593
本文介绍如何在 JavaScript 中利用单链表结构实现前端队列。通过定义 ChainQueue 类,封装了数组初始化、批量与单个元素入队(entryQueue/entryArrQueue)、指定回调的出队(deleteQueue)、获取队首(front)及清空队列(clear)等核心方法。代码包含最大容量限制与类型断言逻辑,适用于前端业务中如订单处理、弹窗管理等需要排队处理的场景。
前端队列应用场景
使用场景
- 例如前端业务中涉及队列处理的需求,
- 比如用户下单后需要触发特定的弹窗提示。
队列类定义与初始化
首先声明一个类
接收一个数组对象:items
class ChainQueue {
constructor(items) {
this.items = items || []
this.maxNum = 200
}
}
入队操作实现
为队列添加数组队列
// 添加数组队列
entryArrQueue(node) {
Array.isArray(node)
node.map(item => this.items.push(item))
}
为当前队列添加单个对象
// 添加队列
entryQueue(node) {
if (this.items.length > this.maxNum) {
return
}
if (Array.isArray(node)) {
node.map(item => this.items.push(item))
} else {
this.items.push(node)
}
}
出队与辅助方法
删除队列,返回删除的当前的项目
deleteQueue(func = () => {}) {
assert(isFunc(func), `${func} is not function`)
func(this.items.shift())
}
返回队列的第一个
front() {
return this.items[0]
}
清除队列
clear() {
this.items = []
}
所有代码
const isFunc = v => typeof v === 'function'
const assert = (condition, msg) => {
if (!condition) throw new Error(`[dashboard]${msg}`)
}
class ChainQueue {
constructor(items) {
this.items = items || []
this.maxNum = 200
}
// 添加数组队列
entryArrQueue(node) {
Array.isArray(node)
node.map(item => this.items.push(item))
}
// 添加队列
entryQueue(node) {
if (this.items.length > this.maxNum) {
return
}
if (Array.isArray(node)) {
node.map(item => this.items.push(item))
} else {
this.items.push(node)
}
}
// 删除队列,返回删除的当前的项目
deleteQueue(func = () => {}) {
assert(isFunc(func), `${func} is not function`)
func(this.items.shift())
}
// 返回队列的第一个
front() {
return this.items[0]
}
// 清除队列
clear() {
this.items = []
}
get size() {
return this.items.length
}
get isEmpty() {
return !this.items.length
}
print() {
console.log(this.items.toString())
console.log(this.items)
}
result() {
return this.items
}
}
module.exports = ChainQueue
// export default ChainQueue
// export default (ChainQueue = new ChainQueue())
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
作者最新文章
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
