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
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
Share Improve this question edited Aug 1, 2012 at 6:23 swapy 1,6161 gold badge15 silver badges32 bronze badges asked Aug 1, 2012 at 6:00 user1562652user1562652 1252 gold badges3 silver badges13 bronze badges 05 Answers
Reset to default 5You 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 ments, 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();
This is easily solved with a bination of addition operators and modulus %
.
x = 0;
//loop
x = (x+4)%24;
Demo: http://jsbin./okereg/1/edit
Following will help
function fnAddVal(val) {
if (val >= 20)
return 0;
else
return val+4;
}
Simple!
x = (x + 4) % 24;
Do you want an infinite loop? What?
You can try something like this for your loop:
<html>
<body>
<script language="javascript">
int x = 0;
while ( x <= 20 )
{
alert("The number is " + x)
if ( x >= 20 )
{
x = 0;
}
x += 4;
}
</script>
</body>
</html>