how could i generate a loop that iterates through a array, and its just multiplying the next index?
example:
array= [0,1,2,3,4,5]
JavaScript
x
6
1
0x1
2
1x2
3
2x3
4
3x4
5
4x5
6
i know that i need to have a nested loop, but I cannot find the solution.
JavaScript
1
10
10
1
for (let i = 0; i < Positions.length; i++) {
2
for (let j = 1; j < Positions.length; j++) {
3
4
5
console.log(Positions[i].number * Positions[j].number )
6
7
}
8
9
}
10
Advertisement
Answer
The problem with your current implementation is that you are looping over every index twice: once for the outer loop and once for the inner loop. To get the item at the index after i
you can simply write Positions[i + 1].number
.
You should loop over every index once like this:
JavaScript
1
4
1
for(let i = 0; i < Positions.length - 1; i++) {
2
console.log(Positions[i] * Positions[i + 1])
3
}
4