I’d like to learn to count the number of elements in the body or within a specific div in my DOM with javascript. What’s a simple way to do this accurately?
There don’t seem to be any tutorials for this that I can find, so I figured it’d be a good question for SO.
asked Jun 12, 2014 at 21:06
The easiest way is simply:
var numOfElements = document.getElementsByTagName('*').length;
Or, to find those elements within a given element:
var element = document.getElementById('demo'),
numElems = element.getElementsByTagName('*').length;
s3c
1,44519 silver badges25 bronze badges
answered Jun 12, 2014 at 21:08
David ThomasDavid Thomas
248k51 gold badges376 silver badges409 bronze badges
0
You can use querySelectorAll
to quickly select elements using CSS selectors. You you want to count every single element you can just do:
var num = document.querySelectorAll('*').length;
If you want to count all elements in a div you can do this:
var num = document.querySelectorAll('#id *').length;
answered Jun 12, 2014 at 21:09
nickclawnickclaw
7085 silver badges11 bronze badges
3
Теги: javascript, js, массив, объект, length, определить количество элементов
В этой статье мы поговорим, как определить число элементов в JavaScript-объекте. Заодно посмотрим, как определяют количество элементов в массиве. И, разумеется, приведём практические примеры.
Как известно, люди нередко ищут сложные пути для решения достаточно простых задач. Так и здесь: определить количество элементов в массиве или объекте, по сути, несложно. Об этом и поговорим.
Итак, давайте представим, что у нас есть объект:
var myObject = new Object(); myObject["firstname"] = "Лев"; // Имя myObject["lastname"] = "Толстой"; // Фамилия myObject["age"] = 21; // ВозрастИ возникает закономерный вопрос: каким образом лучше рассчитать величину объекта, то есть количество входящих в него элементов? Смотрите, если подсчёт будет осуществляться в современных браузерах, то самый простой способ — следующий:
var size = Object.keys(myObject).length;Если же вам нужно обеспечить поддержку старых браузеров, может, пригодится и немного другой вариант:
// Функция, определяющая величину объекта Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // В переменной size будет содержаться количество элементов объекта var size = Object.size(myObject);В принципе, ничего сложного нет. Давайте закрепим этот небольшой урок:
1. Если надо определить число элементов в массиве JavaScript://Определяем массив var arr = ["elem_1", "elem_2", "elem_3", "elem_4", "elem_5"]; //Узнаём число элементов массива, применяем к нему свойство length var countElementsArr = arr.length; //Распечатываем результат в консоль console.log(countElementsArr);2. Если надо определить число элементов в объекте JavaScript:
//Определяем объект var obj = {"first_name": "Ivan", "last_name": "Ivanov", "city": "Ivanovo", "country": "Russia"}; //Узнаём число элементов объекта var countElementsObj = Object.keys(obj).length; //Распечатываем результат в консоль console.log(countElementsObj);Источники:
- https://wordpressrus.ru/javascript/javascript-opredelenie-razmera-massiva-i-obekta.html
- https://wppw.ru/vo/kak-opredelit-kolichestvo-elementov-v-obekte-javascript
Если же интересуют не базовые знания, а действительно продвинутые навыки по разработке на JavaScript, записывайтесь на наши курсы:
Introduction
An array is used to store an ordered collection of values. These values could be a combination of either the same data type or numerous data types — integers, floats, strings, boolean, objects, and lots more.
Getting the number of elements in an array with JavaScript is a common operation when consuming data or working with APIs in JavaScript. This can be accomplished either by utilizing the length
property or iterating through an array and counting the elements.
In this article, we will learn how to get the number of elements in an array with JavaScript and much more — how to count unique elements and how to count elements of an array based on certain conditions.
Using the Built-in length Property
The standard way to get the total number of elements in an array is to use the built-in length
property:
let myArray = [99, 101.5, "John Doe", true, { age: 44 }];
let total = myArray.length;
console.log(total); // Output: 5
// Alternatevly:
let total = [99, 101.5, "John Doe", true, { age: 44 }].length;
console.log(total); // Output: 5
Note: length
refers to a cached value of the length of the array, computed when the array is being created. Therefore, you don’t iterate the array by calling length
explicitly, nor implicitly. This ensures that length
scales up to an arbitrary level and doesn’t impact the performance of your application, such as the impact you’d feel when manually looping through.
Using Loops in JavaScript
JavaScript loops can also be used to count the length of an array by iterating through the array and incrementing the counter variable by one for each element in the array. This is mostly used when you want to perform certain operations on the elements themselves or on a particular element since we are iterating through all the elements in the array.
Note: This approach harder compared to the previously described length
property, though, it’s pretty simple in and of itself. It’s worth noting that longer arrays take longer to iterate through, while length
returns the cached value with a constant lookup time.
for Loop
let myArray = [99, 101.5, "John Doe", true, { age: 44 }];
// Counter variable
let total = 0;
for (let i = 0; i < myArray.length; i++) {
total++;
}
console.log(total); // Output: 5
for…in Loop
let myArray = [99, 101.5, "John Doe", true, { age: 44 }];
let total = 0;
for (i in myArray) {
total++;
}
console.log(total); // Output: 5
Get the Number of Unique Elements in an Array
Arrays in JavaScript can have multiple elements of different data types and these elements could include some duplicates. If we want to get the number of unique elements we can use the Set()
constructor.
It creates a set out of the array passed as its argument. Therefore it helps us remove duplicates and returns only unique elements (a set is a collection of unique elements). When duplicates are removed, we can use the length
property to get the number of unique elements.
For example, suppose we have an array of names that has a total of 7 elements, among which 6 are unique. We can get the unique elements first and then make use of the length
property to get the length:
let names = ["John", "Dan", "Jane", "Sam", "Alisa", "John", "Pete"];
let uniqueNames = [...new Set(names)];
let totalPeople = uniqueNames.length;
console.log(totalPeople); // Output: 6
Note: This can also work with loops. After we get the unique elements stored in a new array, all we have to do is to loop it through and count elements as we’ve done earlier.
What If an Array Contains Other Arrays as Elements?
As we’ve stated before, arrays in JavaScript can contain elements of many data types — including an Array
data type. This may be a bit confusing at first, but when you get a grasp on how length
property counts those subarrays, you are going to be able to handle this situation without any problems.
The first method that probably goes to mind is to use the length
property:
let myArray = [["John", "Pete"], [90, 2], [], [34, 45, 2], [9,4], "John Doe", true, [19]];
let total = myArray.length;
console.log(total); // Output: 8
Note how the length
property treats each subarray as one element. It doesn’t consider the contents of subarrays — no matter if it’s empty or it has a large number of elements, it is counted as one element of the original array (in this case, myArray
).
Get the Number of Elements in an Array Containing Other Arrays
Let’s now learn how to count the number of all elements in an array — including those elements inside subarray elements. We can use a couple of approaches, such as a for
loop or a for...in
, etc.
We’ll first initialize the totalLength
to 0, then create a function (myLength()
) which will be used to loop through the array and count the number of its elements. First of all, we need to loop through the original array and consider each of its elements. If the element is not an array, we’ll just increase the totalLength
by 1. On the other hand, if the current element is an array (subarray of the original array), we’ll recursively call the myLength
method to calculate the number of its elements:
let myArray = [["John", "Pete"], [90, 2], [], [34, 45, 2], [9,4], "John Doe", true, [19]];
let totalLength = 0;
const myLength = (array) => {
// For each element of the `myArray`
for (let i in array) {
// If the element is an array
// recursively call `myLength` to calculate
// the length of the current element
// Otherwise, just increment the `totalLength`
if (Array.isArray(array[i])) {
myLength(array[i]);
} else {
totalLength++;
}
}
};
myLength(myArray);
console.log(totalLength); // Output: 12
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Alternatively, you can simply call the flat()
method on myArray
, which flattens it by recursively concatenating all of the elements into a 1D array, and then call length
on the new array:
console.log(myArray.flat().length) // Output: 12
Count Based on Conditions
Like we’ve mentioned earlier, we can also count the number of elements in an array based on certain conditions. For example, suppose we have an array of students which consists of objects, each object containing students name and score:
const students = [
{ name: "John Doe", score: 70 },
{ name: "Jane Doe", score: 40 },
{ name: "Sarah Jane", score: 33 },
{ name: "John Tough", score: 84 },
{ name: "Jabes Tough", score: 64 }
];
We can count the total number of students that score above 60, by looping through each element and counting ones that passed the predefined condition:
let total = 0;
students.forEach((student) => {
if (student.score >= 60) {
total++;
}
});
console.log(total); // Output: 3
This would also work for other iteration methods like the for
loop:
let total = 0;
for (let i = 0; i < students.length; i++) {
if (students[i].score >= 60) {
total++;
}
}
console.log(total); // Output: 3
Conclusion
In this article, we learned how to get the number of elements in an array and we saw various scenarios that could warrant us getting the length of an array and how we could achieve each of them.
To count elements of an array in JavaScript, you can use the “length” property. The “length” property sets or returns the number of elements in an array. The value of a length property is the integer with a positive sign and a value less than 2 to the 32nd power.
Syntax
To set the length of the array, use the array.length =number syntax.
Return Value
The length property returns a Number, representing the number of elements in the array object.
Example
const netflix = ["Stranger Things", "Money Heist", "Loki", "WandaVision"]
let length = netflix.length
console.log(length)
Output
It returns 4, which means the array contains four elements. The length property of an object, an instance of type Array, sets or returns the number of elements in that array.
To count certain elements in the array in JavaScript, you can use the “filter()” function with the length property.
const arr = [11, 21, 19, 21, 46]
const elementToCount = 21;
let count = arr.filter(x => x == elementToCount).length
console.log(count)
Output
In this example, the “filter()” method creates a new array that only contains elements equal to elementToCount.
Then, we used the filtered array’s length property to get the desired element’s count.
You can generalize this to a function to make it reusable:
function countOccurrences(arr, elementToCount) {
return arr.filter(item => item === elementToCount).length;
}
const arr = [1, 2, 3, 2, 1, 2, 3, 1, 1, 1, 2, 3, 3, 3];
console.log(countOccurrences(arr, 1)); // Output: 6
console.log(countOccurrences(arr, 2)); // Output: 4
console.log(countOccurrences(arr, 3)); // Output: 5
This function takes an array arr and an element elementToCount and returns the count of that element in the array. That’s it.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent.
Нам нужно подсчитать количество элементов в массиве javascript. Сколько способов существует для подсчета ячеек массива в javascript. Попробуем вывести вообще все варианты узнать количество элементов в массиве javascript!
Все способы подсчета элементов массива в javascript.
- Количество элементов простого массива javascript
- Количество элементов массива javascript
- Аналог функции count php в javascript.
Количество элементов простого массива javascript
Для простого(одномерного) массива я уже делал аналогичный параграф. Это же свойство применим для того, чтобы узнать количество ячеек массива или количество элементов простого массива(называйте вам, как нравится)
Для того, чтобы найти количество элементов в простом массиве нам понадобится «одномерный массив» :
let arr = [1,2,3,4];
Еще нам нужно, уже упомянутое свойство :
length
И выведем на эран результат подсчета элементов массива с помощью:
Соберем скрипт определения количества ячеек массив вместе:
<script> let arr = [1,2,3,4]; document.write( arr .length);</script>
И разместим выше приведенный код прямо здесь:
Количество элементов ассоциативного массива javascript
Для того, чтобы узнать количество элементов массива нам потребуется:
Метод Object.keys(); , который вернет массив из ключей массива.
Свойство length
И далее вывести получившееся количество элементов массива любым из известных способов… будем использовать document.write();
Узнаем количество элементов в массиве javascript
Создадим ассоциативный массив для тренировки:
let arr_1 = new Array;
arr_1 [«firstname»] = «Вася»;
arr_1 [«lastname»] = «Пупкин»;
arr_1 [«age»] = 21;
Применим «Object.keys»:
Object.keys(arr)
Далее в конце добавим «length»:
Object.keys(arr).length
И выведем с помощью «document.write»:
document.write(Object.keys(arr).length);
Соберем весь код вместе:
<script>
let arr_1 = new Array;
arr_1 [«firstname»] = «Вася»;
arr_1 [«lastname»] = «Пупкин»;
arr_1 [«age»] = 21;
document.write(Object.keys(arr_1).length);
</script>
И теперь выведем код подсчета элементов массива прямо здесь:
Вы спросите… нужен ли «Object.keys»?
Давайте уберем его и выведем таким образом(и посмотрим, что нам выведет эта конструкция):
<script> document.write( arr_1 .length);</script>
Аналог функции count php в javascript.
Не буду делать отельную страницу посвященную аналогу функции «count» — сможете самостоятельно прочитать об этом…
Странно, что в javascript нет похожей функции…
Ну что ж — это нас никогда не останавливало и не остановит! Напишем собственную функцию для подсчета количества элементов в массиве javascript!
function count (obj)
{
var cnt = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) cnt ++;
}
return cnt;
};
Применение функции count в javascript.
Далее… давайте применим к выше приведенным массивам…
В первом пункте одномерный массив:
let arr = [1,2,3,4];
Применим функцию count:
<script> document.write (count ( arr ));</script>
Результат:
Второй массив arr_1 :
<script> document.write (count ( arr_1 ));</script>
Результат:
Не благодарите, но ссылкой можете поделиться!
COMMENTS+
BBcode