Как посчитать количество элементов в массиве js
Перейти к содержимому

Как посчитать количество элементов в массиве js

  • автор:

Array length in javaScript and addressing the confusion

You would think that Array length in javaScript is a trivial matter, and in some respects it might be. However on closer inspection there does seem to be more to it than what might appear to be the case on first inspection. Some might think that the number of elements in an array and the length of an array are one and the same, but that is not really the case actually depending on what you think an element is. If you think that an element can be just simply a kind of slot that can potentially be empty then maybe that is true, else it is not. In any case what I am driving at here is that arrays in javaScript are sparse in nature, and this sparse nature of javaScript arrays can result in problems and confusion if one is not aware of this, and how to go about dealing with it.

One way of thinking about array length might be that Array length in javaScript refers to the highest numbered index value of an array plus one because array length is one rather than zero relative. That is when it comes to the number index values of arrays the numbers start at zero rather than one as with the array length property so often the value of one has to be added and subtracted now in then in expressions to address problems with this. However the value can also be thought of more as just a potential for that actually, as all the elements could be empty elements as the length of an array might not always be the same as what is often called the count of an array.

So then because in some cases array length is just an object property that does not even reflect the highest indexed object key of the array, because there is nothing there actually in some situations. Then in a way it is just a way of declaring an element size of sorts, but many of those elements can be undefined, the default value for an object key that is not there.

The length differs from the size of an array which may refer to the amount of data that an array might take up in memory. There is also what if often called the count of an array that refers to the number of actual declared elements in the array, and that array count might differ in many respects depending on how you go about counting elements in the first place.

So then for the most part, on the surface at least, the length property of an array is easy to understand under a certain light. However there are a few situations that might cause a degree of confusion. So in this post on the subject of array length in javaScript I will take a moment to see about trying to clear up some of the confusion. As such this will be a lengthy post that I will be updating often.

1 — Array length basics in javaScript

For the most part array length in javaScript is a fairly simple and straight forward concept, all Arrays and Array like objects have a length property. This length property is updated each time one or more elements are added to the array, as well as when they are removed using an array prototype method like Array pop, or Array splice. However there is a difference between length, and what is often called count when taking about arrays in js. More on that later in this post, but for now lets cover the basics of array length in javaScript.

Although I will be keeping the examples in this section fairly simple, this is not a getting started type post with javaScript. I assume that you have at least some experience when it comes to getting started with the very basics of javaScript when it comes to running some code in one or more various environments.

— The source code examples and additional notes for this post are on Github

On Github I have my test vjs repository and in a folder of that repository I have the source code examples that I am writing about in this post. There are many other folders, and there all ready is, or at least sooner or later will be a folder for each of my posts on javaScript itself.

1.1 — Array length is one relative, and index values are zero relative

One of the basic concepts to understand about arrays is the nature of array index values in a javaScript programing environment. Arrays in javaScript are Objects that have a numbered set of public key value pairs. So each property of the object that is an element of the array has a numbered index value that can start at the value of zero upwards to the array length minus one.

So in other words these numbered index values are zero relative, meaning that they start at zero and go upward from there, rather than starting at one which would be one relative. So then because the length of an array is one relative, this can often result in inconsistency between length of an array and the index values of an array, however this can easily be adjusted by subtracting or adding one.

1.2 — Array length, count, and Array index

An array has a length property and in most situations the length property is also the number of actual elements in the array as well. However this is not always the case depending on how you go about counting elements. So an arrays count of elements might differ from the length of the array depending on the methodology used to count elements, or potential elements if you prefer. One way of putting it would be thinking of an empty liter sized bottle, it might be an empty bottle but it still has a capacity of one liter. The length of an array could be thought of as the liter bottle itself, and the count of an array can be thought of as whatever amount of volume of something is filling that array.

In addition to the length of an array, and the count of the elements in the array there is also the array index value. This is often a number or a string that can be easily converted to a number that reflects the index of a certain element in an array. That being said there are at least three general numerical values of interest when it cokes to working with an array then, the max capacity or array length, the element count, and the current index value when it comes to looping over the contents of an array.

In the above example I have an array that was created from an object that has numbered key value pairs, and a length property that has a value greater than the number of other keys in the object. Also the numbed keys of the object are going up by multiples of two, and there are four keys in the object aside from the length key. This hopefully helps to give a clear understanding of what the differences are between array length, count, and an index value.

1.3 — Pushing in new elements increases length

When using a method like Array.push to add new elements to an array, the length will be updated each time. In the following example I am just creating an empty array with the array literal syntax, pushing in a new element for each iteration, and also logging the current length each time.

As expected the length of the array goes from one upwards to five as I am logging the length after pushing in new elements to it. Fairly simple of course, but in some situations things can get a little confusing when it comes to adding elements to an array in other ways, as well as when removing them.

1.4 — Popping out old elements decreases length

So also as expected popping out old elements from an array will result in the length decreasing. Here again I have a very simple example where I am just removing elements from an array with the Array.pop method one at a time on each iteration of a loop. As this happens the length decreases with each iteration of the loop as elements are removed from the end of the array with Array.pop.

There are of course many other ways to remove elements from an array that will result in a decrees of length, however there are also some ways to do so that will not. This is of course where things get a little confusing and why it is important to understand the difference between array length and array count as I have covered in the previous sub section of this post on length, count and index values of an array in javaScript.

1.5 — Setting an array element to a high index value will set the length of the Array

ANother way to end up setting array length is by using the bracket syntax to set a numbers index value higher than the current length. Take into account a basic example such as this for a moment.

Here we have an array with a length of 11, but in a way there is only six elements in the array when it comes to a basic way of counting elements. This is what I am talking about when it comes to the difference between array length and array count. The length of the array is just the highest defined index value of he array plus one, while the count of an array is the actual count of defined elements in the array.

1.6 — Array length and array count with Object.keys

So the length of an array can be found by simply taking a look at the current value of the length property of an array, but the count must be obtained by some other means such as using the Object.keys static method which can be used to get an array of public keys of any object including arrays.

The Object.keys method will work fine for a simple example such as this, but in some cases it will result in unexpected results when dealing with an array that has some additional public keys attached to it.

1.7 — length, and count is not always what is expected when dealing with associative Arrays

So say I have an array that has some elements added to it that are attached to indexed key names as usual with an array, but then some that are attached to key names that are not numbered index key values but non numbed string values. This will result in what might be an undesired array count with Object.keys.

This is because of the nature of the Object.keys method, it will give an array of all public key names of an object. In javaScript an Array is a kind of Object, so I can still do anything with it that I could with any other object such as adding additional public keys that are not numbered index values. So when trying to get the count of an array the Object.keys method might not always be the best option, more on array count later in this post.

2 — Setting the length property of an array, and Sparse array basics

It is possible to set the length property of an array by just making use of the assignment operator to given it a new length. When setting a length that is lower than the current length that will result in what would be expected which is the array will end up being truncated to that length that was set. In that event any and all elements at the index value of the length upwards will be lost. So then this can serve as a kind of way of just purging a whole bunch of elements from an index value upwards, but there are maybe better ways of doing so such as using the array splice method.

Setting a higher length property will result in a situation in which any index values above the previous length will result in being empty elements. This might result in unexpected behavior with some array methods like Array forEach or the array map method as they will skip over such elements. So in this section I will be going over a few examples of setting the length of an array, and also touch base more on sparse arrays.

2.1 — Basic set length of array example

For a basic example of setting the length of an array and what happens to an array when doing this, I have this example where I start off with a simple 1,2,3 number array. So the starting length of this array is a length of 3, and each element is defined and has a number value. When I set the length of this array to 1, the result is then all but the first element now remaining in the array. If I then set the length of the array back to a higher value then that of the current length of 1, lets say 5, then the result is a sparse array. The array is sparse because the length of the array is 5, but it is now only element index 0 that is defined, the remaining elements are not event undefined then are not defined, and as such they are just empty element locations.

2.2 — Having a print method using array for each, and setting length

To get a better idea of why this will cause problems try using an array prototype method such as the array for each method, and see what happens. The result will be that the array for each method will not call the function it is given for any and all empty element locations.

3 — Array length when making an array from an object

So in javaScript Arrays are created with the Array constructor, or more often the Array literal syntax. The way that arrays or array like objects are structured is one or more numbered key value pares with a corresponding length property that is often the element count of this kind of object.

3.1 — The array from method

The array from method is on way to go about creating an array from a plain object that is formated like an array in terms of the own properties of the object.

Understanding this can help eliminate confusion with some situations in which the length of an array is in fact really not the length of the array. In this section I will cover some more examples like this to help elaborate more with this.

3.2 — Just a length property with empty elements

It is possible to have an array that has a set length, but all of the elements are undefined. This is the case if the array is created from an object that just has a length property. A similar situation can happen if the array is created with the Array constructor syntax and given an argument that will be the length of the array.

Yet another good example of why it is that length differs from the actual element count of an array.

4 — Negative index values

It is possible to set negative index values for an array. When doing so this might result in unexpected length values as negative index values will not be counted.

However as long as the index values are enumerable the Object.keys method can be used to get an array of enumerable keys for an object, including possible negative index values. Which would be one way to get the true index value if these negative index values are to be counted.

5 — Array count, and ways of getting an actual element count

Say you are dealing with an object that also has some named object keys, and a single index value that is way ahead of the others which results in one or more empty element index positions. As I have covered in a previous section the length property of an array in javaScript is often just the highest index value plus one, however in some cases it is not even that it is just a property of an object actually. In other words it is possible to have an object with just a length property of say 5, but no numbered public keys, so in that case we are dealing with an array that has a length of 5, but a count of 0. This is true if we define the count of an array as the number of public numbered keys between and including, zero to one less the length of an array that are defined keys that contain a value that can even be the undefined value. The reason why is because a key can be define, but contain a value that is undefined actually.

However there are a number of ways to go about getting the actual count of elements in an array, and the meaning of what a count is to begin with can change to mean a whole bunch of different things actually. So in this section I will be taking a stab at all the various kinds of way that one count define what a “count” if an array could be.

5.1 — Object.keys and Object.values

There are two static methods of the main Object Object in core javaScript that in most cases will work okay for getting element count, but there are some drawbacks to be aware of.

The Object.keys method can be used to get an array of enumerable key names of an object, and the Object.values method can be used to get an array of the corresponding values. Then there is Object.getOwnPropertyNames that can be used to get all of the objects own Property names even ones like length, and any additional key value pairs that are set to be not enumerable.

One drawback to using these methods as a way to obtain element count of an array is that if some additional named properties are added to the array that will effect the count, to resolve this a method that involves just counting the positive numbered keys of the array.

5.2 — Just loop for Array count

So one way of getting actual element count that comes to mind is to just loop from zero to the length of the array of vice versa and preform some kind of condition for each for each potential element to determine if there is actually something there or not.

This presents some issues of concern when it comes to arrays with a length property that might be set to a very high number for example. It is a silly waste of resources to loop over all those undeclared numbered key values, when I could find some way to just filter a list of declared key values that can be obtained via the Object.keys static method.

5.3 — Get Array count with Array.filter

So another way to get the actual count of an array would be to still use a method like Object.keys, but filter the results of that method. The Array filter method could be used as a way to create an array of Object keys that are numbered keys equal to or grater than that of zero. The length of that array could then be used as a way to determine the count or an array.

The expression could be tweaked to preform additional checks such as weather or not object keys that are declared but set to undefined should be counted or not.

6 — Typed Arrays and length

When working with typed arrays the length property refers to the number of bit sized units the array is. For example if it is a Unit16Array and it has 3 elements the length of it is 3, and the byte length of it is 6.

The length of an array generally refers to the number of elements, or the highest index value plus one. It does not always refer to the the size of the array in terms of data.

7 — The delete operator and Array length

So in javaScript there is the delete operator which can be used to delete object properties. Once might thing that using it might effect array length, but it does not. It would seem that it is no different from just setting an array element to undefined. So then it does not behave as one might expect when it comes to using the delete keyword to remove elements from an array.

This is of course a very untypical way of deleting elements from an array though. In fact I can not say I use the delete keyword very often, in fact at all in just about any project so far.

7.1 — Deleting a source object property will effect length sometimes though

Although using the delete keyword to delete an array element will not effect length, deleting a property of an object that will be used to create an array might effect the resulting length of that array.

8 — Conclusion

So in javaScript array length is fairly easy to understand, but there are some things about it that can result in some confusion. There can be a difference between the length of an array and the actual element count for example. The length property is really only just a property of an object that reflects the highest element index of the array, and the array could be nothing but empty elements. There are also many little tricks about array length when it comes to setting the value of the length property of an array as a way to delete unwanted elements at the end of an array, and atypical ways of creating arrays fro plain old objects that juts have a length property.

In nay case I hope you enjoyed this post on array length in javaScript, I am sure that I have still managed to not cover everything when it comes to array length in javaScript alone, let alone the subject in general. If you have anything of relevant interest to add be sure to bring it up in the comments if you feel compelled to do so. Thank you for reading.

Array.length

Свойство length объекта, который является экземпляром типа Array , устанавливает или возвращает число элементов этого массива. Значение данного свойства 32-битное безнаковое целое число, которое всегда численно больше чем самый наибольший индекс в массиве.

Синтаксис

Описание

Свойство length является целым числом с положительным знаком и значением, меньшим чем 2 в степени 32 (232).

В любой момент вы можете установить свойство length для обрезки массива. Когда вы расширяете массив, изменяя его свойство length , реальное количество элементов в массиве увеличивается; например, если вы установите свойство length в 3, когда оно равно 2, массив будет из 3 элементов, где значение третьего элемента будет равно undefined .

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

Атрибуты свойства Array.length
Записываемое да
Перечисляемое нет
Настраиваемое нет

Примеры

Пример: итерирование по массиву

В следующем примере массив numbers итерируется до значения свойства length , показывающего, сколько элементов содержит массив. Значение каждого элемента удваивается.

Пример: сокращение массива

Следующий пример сокращает массив statesUS до длины в 50 элементов, если текущая длина массива больше 50.

Массивы

Объекты позволяют хранить данные со строковыми ключами. Это замечательно.

Но довольно часто мы понимаем, что нам необходима упорядоченная коллекция данных, в которой присутствуют 1-й, 2-й, 3-й элементы и т.д. Например, она понадобится нам для хранения списка чего-либо: пользователей, товаров, элементов HTML и т.д.

В этом случае использовать объект неудобно, так как он не предоставляет методов управления порядком элементов. Мы не можем вставить новое свойство «между» уже существующими. Объекты просто не предназначены для этих целей.

Для хранения упорядоченных коллекций существует особая структура данных, которая называется массив, Array .

Объявление

Существует два варианта синтаксиса для создания пустого массива:

Практически всегда используется второй вариант синтаксиса. В скобках мы можем указать начальные значения элементов:

Элементы массива нумеруются, начиная с нуля.

Мы можем получить элемент, указав его номер в квадратных скобках:

Мы можем заменить элемент:

…Или добавить новый к существующему массиву:

Общее число элементов массива содержится в его свойстве length :

Вывести массив целиком можно при помощи alert .

В массиве могут храниться элементы любого типа.

Список элементов массива, как и список свойств объекта, может оканчиваться запятой:

«Висячая запятая» упрощает процесс добавления/удаления элементов, так как все строки становятся идентичными.

Получение последних элементов при помощи «at»

Допустим, нам нужен последний элемент массива.

Некоторые языки программирования позволяют использовать отрицательные индексы для той же цели, как-то так: fruits[-1] .

Однако, в JavaScript такая запись не сработает. Её результатом будет undefined , поскольку индекс в квадратных скобках понимается буквально.

Мы можем явно вычислить индекс последнего элемента, а затем получить к нему доступ вот так: fruits[fruits.length — 1] .

Немного громоздко, не так ли? Нам нужно дважды написать имя переменной.

К счастью, есть более короткий синтаксис: fruits.at (-1) :

Другими словами, arr.at(i) :

  • это ровно то же самое, что и arr[i] , если i >= 0 .
  • для отрицательных значений i , он отступает от конца массива.

Методы pop/push, shift/unshift

Очередь – один из самых распространённых вариантов применения массива. В области компьютерных наук так называется упорядоченная коллекция элементов, поддерживающая два вида операций:

  • push добавляет элемент в конец.
  • shift удаляет элемент в начале, сдвигая очередь, так что второй элемент становится первым.

Массивы поддерживают обе операции.

На практике необходимость в этом возникает очень часто. Например, очередь сообщений, которые надо показать на экране.

Существует и другой вариант применения для массивов – структура данных, называемая стек.

Она поддерживает два вида операций:

  • push добавляет элемент в конец.
  • pop удаляет последний элемент.

Таким образом, новые элементы всегда добавляются или удаляются из «конца».

Примером стека обычно служит колода карт: новые карты кладутся наверх и берутся тоже сверху:

Массивы в JavaScript могут работать и как очередь, и как стек. Мы можем добавлять/удалять элементы как в начало, так и в конец массива.

В компьютерных науках структура данных, делающая это возможным, называется двусторонняя очередь.

Методы, работающие с концом массива:

Удаляет последний элемент из массива и возвращает его:

И fruits.pop() и fruits.at(-1) возвращают последний элемент массива, но fruits.pop() также изменяет массив, удаляя его.

Добавляет элемент в конец массива:

Вызов fruits.push(. ) равнозначен fruits[fruits.length] = . .

Методы, работающие с началом массива:

Удаляет из массива первый элемент и возвращает его:

Добавляет элемент в начало массива:

Методы push и unshift могут добавлять сразу несколько элементов:

Внутреннее устройство массива

Массив – это особый подвид объектов. Квадратные скобки, используемые для того, чтобы получить доступ к свойству arr[0] – это по сути обычный синтаксис доступа по ключу, как obj[key] , где в роли obj у нас arr , а в качестве ключа – числовой индекс.

Массивы расширяют объекты, так как предусматривают специальные методы для работы с упорядоченными коллекциями данных, а также свойство length . Но в основе всё равно лежит объект.

Следует помнить, что в JavaScript существует 8 основных типов данных. Массив является объектом и, следовательно, ведёт себя как объект.

Например, копируется по ссылке:

…Но то, что действительно делает массивы особенными – это их внутреннее представление. Движок JavaScript старается хранить элементы массива в непрерывной области памяти, один за другим, так, как это показано на иллюстрациях к этой главе. Существуют и другие способы оптимизации, благодаря которым массивы работают очень быстро.

Но все они утратят эффективность, если мы перестанем работать с массивом как с «упорядоченной коллекцией данных» и начнём использовать его как обычный объект.

Например, технически мы можем сделать следующее:

Это возможно, потому что в основе массива лежит объект. Мы можем присвоить ему любые свойства.

Но движок поймёт, что мы работаем с массивом, как с обычным объектом. Способы оптимизации, используемые для массивов, в этом случае не подходят, поэтому они будут отключены и никакой выгоды не принесут.

Варианты неправильного применения массива:

  • Добавление нечислового свойства, например: arr.test = 5 .
  • Создание «дыр», например: добавление arr[0] , затем arr[1000] (между ними ничего нет).
  • Заполнение массива в обратном порядке, например: arr[1000] , arr[999] и т.д.

Массив следует считать особой структурой, позволяющей работать с упорядоченными данными. Для этого массивы предоставляют специальные методы. Массивы тщательно настроены в движках JavaScript для работы с однотипными упорядоченными данными, поэтому, пожалуйста, используйте их именно в таких случаях. Если вам нужны произвольные ключи, вполне возможно, лучше подойдёт обычный объект <> .

Эффективность

Методы push/pop выполняются быстро, а методы shift/unshift – медленно.

Почему работать с концом массива быстрее, чем с его началом? Давайте посмотрим, что происходит во время выполнения:

Просто взять и удалить элемент с номером 0 недостаточно. Нужно также заново пронумеровать остальные элементы.

Операция shift должна выполнить 3 действия:

  1. Удалить элемент с индексом 0 .
  2. Сдвинуть все элементы влево, заново пронумеровать их, заменив 1 на 0 , 2 на 1 и т.д.
  3. Обновить свойство length .

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

То же самое происходит с unshift : чтобы добавить элемент в начало массива, нам нужно сначала сдвинуть существующие элементы вправо, увеличивая их индексы.

А что же с push/pop ? Им не нужно ничего перемещать. Чтобы удалить элемент в конце массива, метод pop очищает индекс и уменьшает значение length .

Действия при операции pop :

Метод pop не требует перемещения, потому что остальные элементы остаются с теми же индексами. Именно поэтому он выполняется очень быстро.

Аналогично работает метод push .

Перебор элементов

Одним из самых старых способов перебора элементов массива является цикл for по цифровым индексам:

Но для массивов возможен и другой вариант цикла, for..of :

Цикл for..of не предоставляет доступа к номеру текущего элемента, только к его значению, но в большинстве случаев этого достаточно. А также это короче.

Технически, так как массив является объектом, можно использовать и вариант for..in :

Но на самом деле это – плохая идея. Существуют скрытые недостатки этого способа:

Цикл for..in выполняет перебор всех свойств объекта, а не только цифровых.

В браузере и других программных средах также существуют так называемые «псевдомассивы» – объекты, которые выглядят, как массив. То есть, у них есть свойство length и индексы, но они также могут иметь дополнительные нечисловые свойства и методы, которые нам обычно не нужны. Тем не менее, цикл for..in выведет и их. Поэтому, если нам приходится иметь дело с объектами, похожими на массив, такие «лишние» свойства могут стать проблемой.

Цикл for..in оптимизирован под произвольные объекты, не массивы, и поэтому в 10-100 раз медленнее. Увеличение скорости выполнения может иметь значение только при возникновении узких мест. Но мы всё же должны представлять разницу.

В общем, не следует использовать цикл for..in для массивов.

Немного о «length»

Свойство length автоматически обновляется при изменении массива. Если быть точными, это не количество элементов массива, а наибольший цифровой индекс плюс один.

Например, единственный элемент, имеющий большой индекс, даёт большую длину:

Обратите внимание, что обычно мы не используем массивы таким образом.

Ещё один интересный факт о свойстве length – его можно перезаписать.

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

Таким образом, самый простой способ очистить массив – это arr.length = 0; .

new Array()

Существует ещё один вариант синтаксиса для создания массива:

Он редко применяется, так как квадратные скобки [] короче. Кроме того, у него есть хитрая особенность.

Если new Array вызывается с одним аргументом, который представляет собой число, он создаёт массив без элементов, но с заданной длиной.

Давайте посмотрим, как можно оказать себе медвежью услугу:

Как мы видим, в коде, представленном выше, в new Array(number) все элементы равны undefined .

Чтобы избежать появления таких неожиданных ситуаций, мы обычно используем квадратные скобки, если, конечно, не знаем точно, что по какой-то причине нужен именно Array .

Многомерные массивы

Массивы могут содержать элементы, которые тоже являются массивами. Это можно использовать для создания многомерных массивов, например, для хранения матриц:

toString

Массивы по-своему реализуют метод toString , который возвращает список элементов, разделённых запятыми.

JavaScript: определяем количество элементов в объекте

В этой статье мы поговорим, как определить число элементов в JavaScript-объекте. Заодно посмотрим, как определяют количество элементов в массиве. И, разумеется, приведём практические примеры.

Как известно, люди нередко ищут сложные пути для решения достаточно простых задач. Так и здесь: определить количество элементов в массиве или объекте, по сути, несложно. Об этом и поговорим.

Итак, давайте представим, что у нас есть объект:

И возникает закономерный вопрос: каким образом лучше рассчитать величину объекта, то есть количество входящих в него элементов? Смотрите, если подсчёт будет осуществляться в современных браузерах, то самый простой способ — следующий:

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

В принципе, ничего сложного нет. Давайте закрепим этот небольшой урок: 1. Если надо определить число элементов в массиве JavaScript:

2. Если надо определить число элементов в объекте JavaScript:

  • https://wordpressrus.ru/javascript/javascript-opredelenie-razmera-massiva-i-obekta.html
  • https://wppw.ru/vo/kak-opredelit-kolichestvo-elementov-v-obekte-javascript

Если же интересуют не базовые знания, а действительно продвинутые навыки по разработке на JavaScript, записывайтесь на наши курсы:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *