Reputation: 11
I want to increment a var with 1 every 100 presses. I can't write 100 else ifs for every one hundred.
var age = 18;
var counter = 0;
function work() {
counter++;
if (counter == 100 ) {
age++;
} else if (counter == 200) {
agee++;
}
}
Upvotes: 0
Views: 578
Reputation: 1
You can use (counter % 100 === 0 ) condition, so whenever there is a counter which is divisible by 100 then it would return true. % operator - gives the remainder
scenario 1 : counter is between 0 - 99 then no increment in age.
scenario 2 : counter reaches 100 and age get incremented.
scenario 3 : counter is between 101 - 199 then no increment in age.
scenario 4 : counter reaches 200 and age get incremented.
var age = 18;
var counter = 200;
function work() {
counter++;
console.log("counter "+counter);
if (counter% 100 === 0 ){
age++;
}
console.log(age);
}
work();
counter = 399; // Just for testing purpose
work();
console.log(age);
Upvotes: 0
Reputation: 1187
Use some modulus division:
var age = 18;
var counter = 0;
function work() {
counter++;
if (counter % 100 == 0) {
age++;
console.log("Age incremented to: " + age + "\nValue of counter: " + counter)
}
}
for (var step = 0; step < 500; step++) {
work()
}
The %
symbol essentially just returns the remainder when divided by the other number (aka modulus division).
Upvotes: 0
Reputation: 387
Try this:
var age = 18;
var counter = 0;
function work() {
counter++;
if (counter % 100 == 0) {
age++;
}
}
Upvotes: 1