const numbers = [1, 2, 3, 4, 6, 7, 8];
let i = -1;
numbers.forEach(n => {
console.log(n);
i = i+1;
});
How is i 6?
const numbers = [1, 2, 3, 4, 6, 7, 8];
let i = -1;
numbers.forEach(n => {
console.log(n);
i = i+1;
});
How is i 6?
i get the following output
1
2
3
4
6
7
8
each element in the array, as expected. What do you use i
for? seems redundant.
quiz problem. it says the value of i at first is 6. I think i just figured it out. 7 elements in the array, at the begging i = -1. so that leaves 6.
If you need the index of the element, it can be passed as a parameter to the forEach, like this:
const numbers = [1, 2, 3, 4, 6, 7, 8];
numbers.forEach((number, index) => {
console.log('number in the array: ’ + number + ', it’s index is: ’ + index);
});
Since it’s two parameters now, and not just the number, you need the parenthesis around the number and index.
(also use string template literals, I only used concatenating because the backticks formatted my comment in a strange way:) )
This will be my output:
number in the array: 1, it’s index is: 0
number in the array: 2, it’s index is: 1
number in the array: 3, it’s index is: 2
number in the array: 4, it’s index is: 3
number in the array: 6, it’s index is: 4
number in the array: 7, it’s index is: 5
number in the array: 8, it’s index is: 6