krahets/hello-algo · error · Error

索引越界

Error message

索引越界

What it means

Thrown by get(index) on a dynamic list when index is negative or >= the current element count (#size). The message ('索引越界', Traditional Chinese for 'index out of bounds') guards the backing-array read #arr[index]. It distinguishes logical size from raw capacity, so unused trailing slots are also rejected.

Source

Thrown at zh-hant/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

  1. Validate 0 <= index < list.size() before calling get.
  2. Prefer iterating with size() as the exclusive upper bound.
  3. Remember capacity() >= size(); never index by capacity.
  4. Catch the error when reading untrusted indices.

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

if (index >= 0 && index < list.size()) {
    return list.get(index);
}

Type guard

function isValidReadIndex(list, index) {
    return Number.isInteger(index) && index >= 0 && index < list.size();
}

Try / catch

try {
    return list.get(index);
} catch (e) {
    if (e instanceof Error && e.message === '索引越界') {
        return undefined;
    }
    throw e;
}

Prevention

When it happens

Trigger: Calling get with an index >= #size (e.g. reading slot #size which exists in the array but is not a live element); passing a negative index; using a loop counter that overshoots by one.

Common situations: Confusing the list's capacity with its size; index math computed against capacity rather than size; off-by-one in for-loops that use <= instead of <.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/6d85b643288fa947. Report an issue: GitHub.