最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

variables - Javascript - increment value by 4. - Stack Overflow

programmeradmin2浏览0评论

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 0
Add a ment  | 

5 Answers 5

Reset to default 5

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 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>
发布评论

评论列表(0)

  1. 暂无评论