重复数字达到极限,然后循环它

Repetition of number up to limit, then loop it

本文关键字:然后 循环 极限 数字      更新时间:2023-09-26

我想在jQuery中这样做:

var limit=3;
if input is 1 ==> the output is 1;
if input is 2 ==> the output is 2;
if input is 3 ==> the output is 3;
//after the limit (in this example 3)
if input is 4 ==> the output is 1;
if input is 5 ==> the output is 2;
if input is 6 ==> the output is 3;
//again
if input is 7 ==> the output is 1;
if input is 8 ==> the output is 2;
if input is 9 ==> the output is 3.
...

我使用了do-while循环,但我希望有一个更好的(就行数而言)功能。

多谢

法比奥

您正在寻找返回除法余数的模运算符。

var x = val % 3;

唯一的区别是,如果值为 0,则需要在值中添加 3(如 3 % 3 == 0

var x = val % 3;
if (val == 0) 
    val = 3;

您可以使用函数使此代码更通用/更有用。

function looped_number(number, limit) {
    var val = number % limit;
    if (val == 0) 
        val = limit;
    return val;
}

您还可以使用逻辑||运算符使上述代码更加简洁。

function looped_number(number, limit) {
    return number % limit || limit;
}

试试这个:

output = input % limit || limit ;