Подсчитать количество элементов массива javascript

JavaScript Array length

The length property sets or returns the number of elements in an array.

Syntax

Return the length of an array:

Set the length of an array:

Return Value

Browser Support

length is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

.length

Свойство, которое возвращает количество элементов в массиве.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Свойство length возвращает количество элементов в массиве. Если элементов нет, то свойство возвращает 0.

Пример

Скопировать ссылку «Пример» Скопировано

 const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс']console.log(series.length)// 4 const empty = []console.log(empty.length)// 0 const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс'] console.log(series.length) // 4 const empty = [] console.log(empty.length) // 0      

Как понять

Скопировать ссылку «Как понять» Скопировано

Свойство length хранит количество ячеек в массиве. Строго говоря, количество ячеек может быть больше, чем количество элементов в массиве, но на практике они почти всегда совпадают.

Значение свойства length — целое положительное число в диапазоне от 0 до 2 32 .

Запись в свойство length

Скопировать ссылку «Запись в свойство length» Скопировано

Свойство length перезаписываемое, вы можете записать в него любое число из диапазона возможных значений. Это изменит количество ячеек массива.

Читайте также:  Решения объекты на php

Если уменьшить значение свойства length , то из конца массива будут отброшены элементы, которые не входят в новый размер массива:

 const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс']console.log(series.length)// 4 series.length = 2console.log(series)// ['Кремниевая долина', 'Игра престолов'] const series = ['Кремниевая долина', 'Игра престолов', 'Рик и Морти', 'Гравити Фолс'] console.log(series.length) // 4 series.length = 2 console.log(series) // ['Кремниевая долина', 'Игра престолов']      

Если увеличить значение свойства length , то в конец массива добавятся пустые ячейки. Значение в них не будет установлено и они будут игнорироваться при обходе:

 const todos = ['купить молока', 'почитать Доку']console.log(todos.length)// 2 todos.length = 4console.log(todos)// ['купить молока', 'почитать Доку', ] todos.forEach(function(todo, index)  console.log(`$. todo`)>)// 1. купить молока// 2. почитать Доку const todos = ['купить молока', 'почитать Доку'] console.log(todos.length) // 2 todos.length = 4 console.log(todos) // ['купить молока', 'почитать Доку', ] todos.forEach(function(todo, index)  console.log(`$index + 1>. todo`) >) // 1. купить молока // 2. почитать Доку      

Случаи, когда length не совпадает с количеством элементов в массиве

Скопировать ссылку «Случаи, когда length не совпадает с количеством элементов в массиве» Скопировано

Корректнее всего говорить, что свойство length хранит количество ячеек доступных для записи в массиве, а не количество элементов. Они почти всегда совпадают, но есть случаи, когда в массиве больше ячеек, чем значений. Разберём эти случаи.

1️⃣ При создании пустого массива с помощью конструктора new Array ( ) можно указать количество ячеек в массиве. Тогда количество ячеек и количество элементов не будут совпадать:

 const emptyArray = new Array(100)console.log(emptyArray.length)// 100 const emptyArray = new Array(100) console.log(emptyArray.length) // 100      

Такой проблемы не случится, если создавать массив с помощью литерала:

 const anotherEmptyArray = []console.log(anotherEmptyArray.length)// 0 const anotherEmptyArray = [] console.log(anotherEmptyArray.length) // 0      

2️⃣ При записи нового элемента в индекс далеко за пределами массива. В этом случае между последним элементом и новым появляется «дыра» из пустых ячеек:

 const priorities = ['спать', 'есть', 'пить']console.log(priorities.length)// 3 priorities[999] = 'работать'console.log(priorities.length)// 1000console.log(priorities)// ['спать', 'есть', 'пить', , 'работать'] const priorities = ['спать', 'есть', 'пить'] console.log(priorities.length) // 3 priorities[999] = 'работать' console.log(priorities.length) // 1000 console.log(priorities) // ['спать', 'есть', 'пить', , 'работать']      

3️⃣ При ручном увеличении значения свойства length :

 const todos = ['купить молока', 'почитать Доку']console.log(todos.length)// 2 todos.length = 4console.log(todos)// ['купить молока', 'почитать Доку', ] const todos = ['купить молока', 'почитать Доку'] console.log(todos.length) // 2 todos.length = 4 console.log(todos) // ['купить молока', 'почитать Доку', ]      

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 Свойство length используется при обходе массивов с помощью классических циклов for или while . На практике такие циклы уже встречаются редко, но это идиоматический код, который нужно знать. Если применить length неправильно, то можно перебрать не все элементы или сделать бесконечный цикл.

Классический код, который напечатает все элементы массива:

 const movies = ['Good Will Hunting', 'Raining Man', 'Beautiful Mind']for (let i = 0; i < movies.length; i++)  console.log(movies[i])> const movies = ['Good Will Hunting', 'Raining Man', 'Beautiful Mind'] for (let i = 0; i  movies.length; i++)  console.log(movies[i]) >      

🛠 Чаще всего к свойству обращаются, когда хотят проверить, пустой массив или нет:

 const movies = [] if (movies.length === 0)  console.log('Вы посмотрели все фильмы!')> const movies = [] if (movies.length === 0)  console.log('Вы посмотрели все фильмы!') >      

🛠 Не записывайте вручную значения в length . Хотя это и возможно, на практике такой код плохо читается. Он может неприятно удивить других разработчиков из-за того, что изменяет размер массива. Об этом побочном эффекте знают не все.

Источник

Array: length

The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Try it

Value

A nonnegative integer less than 2 32 .

Property attributes of Array: length
Writable yes
Enumerable no
Configurable no

Description

The value of the length property is a nonnegative integer with a value less than 2 32 .

const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length 

The array object observes the length property, and automatically syncs the length value with the array’s content. This means:

  • Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.
  • Setting any array index (a nonnegative integer smaller than 2 32 ) beyond the current length extends the array — the length property is increased to reflect the new highest index.
  • Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.

When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots.

const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // set array length to 5 while currently 2. console.log(arr); // [ 1, 2, ] arr.forEach((element) => console.log(element)); // 1 // 2 

Examples

Iterating over an array

In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.

const numbers = [1, 2, 3, 4, 5]; const length = numbers.length; for (let i = 0; i  length; i++)  numbers[i] *= 2; > // numbers is now [2, 4, 6, 8, 10] 

Shortening an array

The following example shortens the array numbers to a length of 3 if the current length is greater than 3.

const numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3)  numbers.length = 3; > console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 console.log(numbers[3]); // undefined; the extra elements are deleted 

Create empty array of fixed length

Setting length to a value greater than the current length creates a sparse array.

const numbers = []; numbers.length = 3; console.log(numbers); // [empty x 3] 

Array with non-writable length

The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode.

"use strict"; const numbers = [1, 2, 3, 4, 5]; Object.defineProperty(numbers, "length",  writable: false >); numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]' numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]' 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью