Skip to content

Commit

Permalink
Добавляет нюанс про разрежённый массив (#5559)
Browse files Browse the repository at this point in the history
Co-authored-by: Vitya <9317613+vitya-ne@users.noreply.github.com>
Co-authored-by: Tatiana Fokina <fokinatatian@gmail.com>
Co-authored-by: Alexey Nikitchenko <nikitchenkoad@gmail.com>
  • Loading branch information
4 people authored Dec 13, 2024
1 parent b91d8e2 commit 095eb9c
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions js/arrays/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ authors:
- nlopin
contributors:
- furtivite
- anastasiayarosh
related:
- js/ref-type-vs-value-type
- js/typecasting
Expand Down Expand Up @@ -171,3 +172,42 @@ console.log(episodesPerSeasons.includes(8))
console.log(episodesPerSeasons.includes(6))
// true
```

Интересно, что если в массиве будут индексы с пропусками, то можно получить разрежённый массив. Предположим, у нас есть набор элементов:

```js
const arr = ['d', 'o', 'k', 'a']
```

Добавим к нему ещё один элемент, так, чтобы его индекс был больше длины всего набора элементов. Мы получим массив с незаполненным элементом (empty slot). Если обратимся к нему по индексу, получим `undefined`:

```js
arr[5] = '!'

console.log(arr)
// Выведет в Firefox ['d', 'o', 'k', 'a', <1 empty slot>, '!']

console.log(arr[4])
// Выведет undefined
```

Длина массива будет включать в себя все элементы, включая незаполненные, то есть в нашем случае не 5 элементов, а 6:

```js
console.log(arr.length)
// Выведет 6
```

Или мы можем взять другой пример:

```js
// Зрители, которые заняли три места в ряду. Индексы их мест: 0, 1, 2
const audience = ['🐸', '🐶', '🐱']

// Опоздавший зритель занял место в темноте и не по порядку!
audience[5] = '🐌'

// Места с индексами 3 и 4 всё ещё свободны, и это логично!
console.log(audience)
// Array(6) [ '🐸', '🐶', '🐱', <2 empty slots>, '🐌' ]
```

0 comments on commit 095eb9c

Please sign in to comment.