krahets/hello-algo · error · Error
队列为空
Error message
队列为空
What it means
Thrown by ArrayQueue.peek() ('队列为空' / queue is empty) when queSize === 0. peek() returns nums[front]; on an empty queue front is stale, so the guard prevents returning undefined-as-number. pop() calls peek() first, so pop on an empty queue surfaces the same error.
Source
Thrown at codes/typescript/chapter_stack_and_queue/array_queue.ts:58
// 通过取余操作实现 rear 越过数组尾部后回到头部
const rear = (this.front + this.queSize) % this.capacity;
// 将 num 添加至队尾
this.nums[rear] = num;
this.queSize++;
}
/* 出队 */
pop(): number {
const num = this.peek();
// 队首指针向后移动一位,若越过尾部,则返回到数组头部
this.front = (this.front + 1) % this.capacity;
this.queSize--;
return num;
}
/* 访问队首元素 */
peek(): number {
if (this.isEmpty()) throw new Error('队列为空');
return this.nums[this.front];
}
/* 返回 Array */
toArray(): number[] {
// 仅转换有效长度范围内的列表元素
const arr = new Array(this.size);
for (let i = 0, j = this.front; i < this.size; i++, j++) {
arr[i] = this.nums[j % this.capacity];
}
return arr;
}
}
/* Driver Code */
/* 初始化队列 */
const capacity = 10;
const queue = new ArrayQueue(capacity);View on GitHub (pinned to 69932aed18)
Solutions
- Guard with isEmpty(): if (!queue.isEmpty()) queue.pop().
- Use while (!queue.isEmpty()) for drain loops.
- Track enqueue/dequeue counts and never dequeue beyond the enqueued total.
Example fix
// before
const head = queue.peek(); // throws when empty
// after
if (!queue.isEmpty()) {
const head = queue.peek();
} Defensive patterns
Strategy: validation
Validate before calling
function safePeek(queue) {
return queue.isEmpty() ? undefined : queue.peek();
} Type guard
null
Try / catch
null
Prevention
- Check queue.isEmpty() before peek/pop.
- Use while (!queue.isEmpty()) for drain loops.
- Track enqueue/dequeue counts; never dequeue past the total.
When it happens
Trigger: Calling pop() or peek() on an empty queue; a consumer loop that dequeues more items than were enqueued.
Common situations: Draining a queue without an isEmpty check; calling peek before any push; a worker that processes faster than the producer and hits an empty window.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/b55910c58bffb4ca.
Report an issue: GitHub.