Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  33] [ 2]  / answers: 1 / hits: 16086  / 12 Years ago, wed, august 1, 2012, 12:00:00

I have a problem.



I need a Javascript function which increase (increment) variable value by 4, and when the variable value is 20, then set value of variable to 0 and again increment it by 4 and so on...



I think that I need for loop and if condition, but I don't know how to implement this...



Example



the result must be:



x = 0; then x = 4, x = 8, x = 12, x = 16, x = 20, x = 0, x= 4 ....



Thank you


More From » variables

 Answers
83

You can do this with a nested pair of loops:



while (true) {
for (var x = 0; x <= 20; x += 4) {
// use x
}
}


This will be more efficient than using the mod (%) operator.



EDIT



From your comments, it sounds like you want to generate the sequence incrementally, rather than in a loop. Here's a function that will return a function that will generate the next element of your sequence each time you call it:



function makeSequence() {
var x = 20; // so it wraps to 0 first time
return function() {
if (x == 20) { x = 0 }
else { x += 4 }
return x;
}
}


You could then use it like this (among many ways):



var sequence = makeSequence();

// and each time you needed the next element of the sequence:

var x = sequence();

[#83932] Tuesday, July 31, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ramseydeshaunc

Total Points: 30
Total Questions: 91
Total Answers: 103

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
;