krahets/hello-algo · error · Error
индекс выходит за границы
Error message
индекс выходит за границы
What it means
Thrown by MyList.get (TS) with message 'индекс выходит за границы' ('index out of bounds') when the requested index is negative or >= the logical size (_size), distinct from the underlying array's capacity. The list tracks a logical length shorter than the backing array, so capacity is not the bound.
Source
Thrown at ru/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
- Loop with j < list.size(), not <=, and never use capacity() as the bound.
- Re-read size() after structural changes before indexing.
- Validate: if (i >= 0 && i < list.size()) list.get(i).
Example fix
// before for (let i = 0; i <= list.size(); i++) list.get(i); // last throws // after for (let i = 0; i < list.size(); i++) list.get(i);
Defensive patterns
Strategy: validation
Validate before calling
function safeGet(list, i) {
if (i < 0 || i >= list.size()) throw new RangeError('bad index');
return list.get(i);
} Type guard
function isIndexInBounds(i, list) {
return Number.isInteger(i) && i >= 0 && i < list.size();
} Prevention
- Loop with i < list.size(), not <=.
- Never use capacity() as a loop bound — it exceeds the logical size.
- Re-read size() after structural modifications before indexing.
When it happens
Trigger: Calling get(index) with index < 0 or index >= this._size. Indices in [_size, _capacity) are reserved/unused and also throw.
Common situations: Off-by-one loops (<= vs <); using the backing array length or capacity as the loop bound instead of size(); reading an index after a remove shifted elements.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/e19a4509f786c0d8.
Report an issue: GitHub.