JavaScript用数组可高效模拟栈(LIFO,push/pop)和队列(FIFO,push/shift),但shift性能较差;可封装成Stack/Queue类提升语义化与复用性。
JavaScript 中没有原生的栈(Stack)和队列(Queue)类型,但可以用数组(Array)高效模拟它们的行为。核心在于控制元素的插入和删除位置:栈是“后进先出”(LIFO),队列是“先进先出”(FIFO)。
栈只允许在一端(通常叫“栈顶”)进行添加(push)和移除(pop)操作。JavaScript 数组的 push() 和 pop() 方法天然适配这一规则。
arr.push(item) —— 添加到末尾arr.pop() —— 移除并返回末尾元素arr[arr.length - 1] 或 arr.at(-1)
arr.length === 0
例如:
const stack = []; stack.push(1); // [1] stack.push(2); // [1, 2] stack.pop(); // 返回 2,stack 变为 [1]
队列需在一头添加(入队)、另一头移除(出队)。数组的 push()(尾部添加)和 shift()(头部移除)可实现,但注意 shift() 在长数组中性能较差(需移动所有后续元素)。
立即学习“Java免费学习笔记(深入)”;
arr.push(item) —— 添加到末尾arr.shift() —— 移除并返回首个元素arr[0] 或 arr.at(0)
arr.length === 0
例如:
const queue = []; queue.push(1); // [1] queue.push(2); // [1, 2] queue.shift(); // 返回 1,queue 变为 [2]
若对性能敏感(如大量出队操作),可用双指针模拟“循环队列”,或借助 Deque(部分环境支持,如 Node.js 18+ 或使用第三方库)。简单起见,日常开发中也可用两个数组交替(如入队存一个数组,出队时批量反转到另一个),但最常用且足够轻量的方式仍是 push + shift,除非明确遇到性能瓶颈。
为提升可读性和复用性,可封装基础类:
class Stack {
constructor() { this.items = []; }
push(x) { this.items.push(x); }
pop() { return this.items.pop(); }
peek() { return this.items[this.items.length - 1]; }
isEmpty() { return this.items.length === 0; }
}
class Queue {
constructor() { this.items = []; }
enqueue(x) { this.items.push(x); }
dequeue() { return this.items.shift(); }
front() { return this.items[0]; }
isEmpty() { return this.items.length === 0; }
}
这样调用更语义化:stack.push(5)、queue.enqueue("msg")。