krahets/hello-algo · error · Error
索引越界
Error message
索引越界
What it means
Thrown by MyList.get(index) (message: '索引越界' = 'index out of bounds') when index < 0 or index >= _size. The guard mirrors standard dynamic-array bounds checking before returning arr[index].
Source
Thrown at zh-hant/codes/typescript/chapter_array_and_linkedlist/my_list.ts:32
/* 建構子 */
constructor() {
this.arr = new Array(this._capacity);
}
/* 獲取串列長度(當前元素數量)*/
public size(): number {
return this._size;
}
/* 獲取串列容量 */
public capacity(): number {
return this._capacity;
}
/* 訪問元素 */
public get(index: number): number {
// 索引如果越界,則丟擲異常,下同
if (index < 0 || index >= this._size) throw new Error('索引越界');
return this.arr[index];
}
/* 更新元素 */
public set(index: number, num: number): void {
if (index < 0 || index >= this._size) throw new Error('索引越界');
this.arr[index] = num;
}
/* 在尾部新增元素 */
public add(num: number): void {
// 如果長度等於容量,則需要擴容
if (this._size === this._capacity) this.extendCapacity();
// 將新元素新增到串列尾部
this.arr[this._size] = num;
this._size++;
}
View on GitHub (pinned to 69932aed18)
Solutions
- Validate 0 <= index < list.size() before calling get.
- Use list.size() (not capacity()) as the loop upper bound.
- When computing an index via subtraction, clamp to >= 0.
Example fix
// before
const val = list.get(index); // throws '索引越界' if out of range
// after
if (index >= 0 && index < list.size()) {
const val = list.get(index);
} Defensive patterns
Strategy: validation
Validate before calling
if (index >= 0 && index < list.size()) {
const val = list.get(index);
} Type guard
function isValidIndex(list: MyList, index: number): index is number {
return Number.isInteger(index) && index >= 0 && index < list.size();
} Try / catch
try {
const val = list.get(index);
} catch (e) {
if (e.message === '索引越界') {
// index out of bounds — handle
} else throw e;
} Prevention
- Use list.size() — not capacity() — as the loop upper bound.
- Clamp computed indices to >= 0 to avoid negative underflow.
- Prefer for...of or indexed loops bounded by size() for reads.
When it happens
Trigger: Calling get(index) with a negative index, or an index >= the number of stored elements.
Common situations: Off-by-one loop bounds; using capacity instead of size for bounds; iterating past the last valid element; negative index from subtraction underflow.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/4498549965c5bc2e.
Report an issue: GitHub.