Currently, I am trying to build a function that does the following thing:
First click: 1, 2, 3, 4, 5, 6, 7
Second click: 8
Third click: 9
JavaScript
x
24
24
1
import { FC, useState } from 'react';
2
3
export const HandOutCards: FC = () => {
4
const [count, setCounter] = useState(0);
5
6
function firstHandOut(counter: number) {
7
let maxLength = 7;
8
for (let i = 0; i < 10; i++) {
9
console.log(i);
10
if (i === (maxLength + counter)) {
11
break;
12
}
13
}
14
}
15
16
const counter = () => {
17
setCounter(count + 1);
18
firstHandOut(count);
19
};
20
21
return (
22
<button onClick={counter}>HandOut</button>
23
);
24
};
But in the snippet the code does this now:
- First click 1, 2, 3, 4, 5, 6, 7
- Second click 1, 2, 3, 4, 5, 6, 7, 8
- Third click 1, 2, 3, 4, 5, 6, 7, 8, 9
How can I only add one index when I have a second or third click.
Advertisement
Answer
You have to save the last count i
to prevent the loop to start from 0
everytime.
If you want to output the first 7 numbers inline you have to call console.log ()
after the for
loop. But you can feed a string in the loop for the final output. (you can use a simple ternary operator to prepend the comma only if its not the first loop)
Working example: (simplified for demonstration)
JavaScript
1
18
18
1
let counter = 0;
2
let last_count = 0;
3
let maxLength = 7;
4
5
function firstHandOut() {
6
let output = '';
7
8
for (let i = last_count + 1; i < 10; i++) {
9
output += (i != last_count + 1 ? ', ' : '') + i;
10
if ((i === (maxLength + counter))) {
11
last_count = i;
12
break;
13
}
14
}
15
16
console.log(output);
17
counter++;
18
}
JavaScript
1
1
1
<button type="button" onclick="firstHandOut();">test</button>