krahets/hello-algo · error · Error
インデックスが範囲外です
Error message
インデックスが範囲外です
What it means
Thrown by MyList.get (Japanese: 'インデックスが範囲外です' = 'index out of range') when index is outside [0, size). The list uses a fixed backing array with a logical size separate from capacity, so get must refuse reads beyond the logical length to avoid returning uninitialized slots.
Source
Thrown at ja/codes/javascript/chapter_array_and_linkedlist/my_list.js:32
/* コンストラクタ */
constructor() {
this.#arr = new Array(this.#capacity);
}
/* リストの長さを取得(現在の要素数) */
size() {
return this.#size;
}
/* リスト容量を取得する */
capacity() {
return this.#capacity;
}
/* 要素にアクセス */
get(index) {
// インデックスが範囲外なら例外を送出する。以下同様
if (index < 0 || index >= this.#size) throw new Error('インデックスが範囲外です');
return this.#arr[index];
}
/* 要素を更新 */
set(index, num) {
if (index < 0 || index >= this.#size) throw new Error('インデックスが範囲外です');
this.#arr[index] = num;
}
/* 末尾に要素を追加 */
add(num) {
// 長さが容量に等しい場合は拡張が必要
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// 新しい要素をリストの末尾に追加する
this.#arr[this.#size] = num;
this.#size++;View on GitHub (pinned to 69932aed18)
Solutions
- Bounds-check 0 <= index < list.size() before get.
- Iterate using size(), never capacity().
- After inserts/removes, recompute the bound before indexing.
Example fix
// before const v = list.get(i); // throws if i >= size // after const v = (i >= 0 && i < list.size()) ? list.get(i) : undefined;
Defensive patterns
Strategy: validation
Validate before calling
const v = (i >= 0 && i < list.size()) ? list.get(i) : undefined;
Type guard
function isValidReadIndex(list, i) {
return Number.isInteger(i) && i >= 0 && i < list.size();
} Try / catch
try { return list.get(i); }
catch (e) { if (!/範囲外/.test(e.message)) throw e; return undefined; } Prevention
- Always iterate using size(), not capacity().
- Refresh bounds after add/remove/insert.
- Clamp external indices to [0, size) before get.
When it happens
Trigger: Calling get with an index >= current size; passing a negative index; using capacity() as the upper bound instead of size().
Common situations: Confusing size with capacity; stale loop bounds after add/remove/insert; off-by-one in for loops.
Related errors
- Index Out Of Bounds Exception
- Index out of bounds
- Illegal Argument Exception
- Illegal Argument Exception
- Heap is empty.
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/c0f1d0996d6ae9be.
Report an issue: GitHub.