Javascript - 将值增加 4。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11753360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:13:02  来源:igfitidea点击:

Javascript - increment value by 4.

javascriptvariablesincrement

提问by user1562652

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...

我需要一个 Javascript 函数,它将变量值增加(增加)4,当变量值为 20 时,然后将变量的值设置为 0,然后再次将其增加 4,依此类推...

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

我认为我需要 for 循环和 if 条件,但我不知道如何实现这个...

Example

例子

the result must be:

结果必须是:

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

x = 0; 那么 x = 4, x = 8, x = 12, x = 16, x = 20, x = 0, x= 4 ....

Thank you

谢谢

回答by Ted Hopp

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.

这将比使用 mod ( %) 运算符更有效。

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();

回答by Joseph Marikle

This is easily solved with a combination of addition operators and modulus %.

这可以通过加法运算符和模数的组合轻松解决%

x = 0;
//loop
x = (x+4)%24; 

Demo: http://jsbin.com/okereg/1/edit

演示:http: //jsbin.com/okereg/1/edit

回答by Codesen

Following will help

以下将有所帮助

function fnAddVal(val) {
     if (val >= 20)
            return 0;
     else
       return val+4;

}

回答by ErikE

Simple!

简单的!

x = (x + 4) % 24;

Do you want an infinite loop? What?

你想要无限循环吗?什么?

回答by Next Door Engineer

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>