Reputation: 1036
How do I return the number of elements in an array using for of loop javascript?
I know how I can use a for
loop
to do this but I was wondering if there is a way to do this with a for of
loop. In this case would using a regular for
loop
be better and or the only way to do this is with a loop?
Regular for loop that prints the number of elements in the array:
const arr = [1, 2, 3, 4];
function logElementForLoop(arr) {
console.log("For Loop");
let elemInArr = 0;
for (let i = 0; i < arr.length; i++) {
elemInArr = i + 1;
}
console.log(elemInArr);
}
logElementForLoop(arr);
Upvotes: 0
Views: 180
Reputation: 4519
Using a for of loop
const arr = [1, 2, 3, 4];
function logElementForLoop(arr) {
console.log("For Loop");
let elemInArr = 0;
for (let i of arr ) {
elemInArr = arr.indexOf(i) + 1;
}
console.log(elemInArr);
}
logElementForLoop(arr);
or simply increment elemInArr
const arr = [1, 2, 3, 4];
function logElementForLoop(arr) {
console.log("For Loop");
let elemInArr = 0;
for (let i of arr ) {
elemInArr++
}
console.log(elemInArr);
}
logElementForLoop(arr)
Upvotes: 1
Reputation: 1610
I guess you are looking for something like for of
or for in
loops
let count = 0
for(const item of array) {
count ++
}
console.log('array contains', count, 'elements')
or
let count = 0
for(const index in array) {
count ++
}
console.log('array contains', count, 'elements')
Upvotes: 2
Reputation: 2549
Well, if you need to count array elements in for loop..? then
const arr = [1, 2, 3, 4, 5];
// Counter var
let counter = 0;
// Count in for loop
for(let i = 0; i < arr.length; i++) counter++;
// Log
console.log(counter);
Upvotes: 1
Reputation: 68933
I was wondering if there is a way to do this with a for of loop...
Yes, it is possible, simply increment the variable (elemInArr) inside the loop:
const arr = [1, 2, 3, 4];
function logElementForLoop(arr) {
console.log("For Loop");
let elemInArr = 0;
for (let i of arr) {
elemInArr++;
}
console.log(elemInArr);
}
logElementForLoop(arr);
Upvotes: 3
Reputation: 386746
You need to add 1
to the count, instead of assigning the index plus one.
function logElementForLoop(arr) {
console.log("For Loop");
let elemInArr = 0;
for (let i = 0; i < arr.length; i++) {
// add one for each element
// elemInArr = elemInArr + 1; // is doing it the long way
// elemInArr += 1; // jsut add one, handy for adding different values than one
elemInArr++; // standard approach
}
console.log(elemInArr);
}
const arr = [1, 2, 3, 4];
logElementForLoop(arr);
Upvotes: 1