gpt4 book ai didi

JavaScript "clockwork arithmetic"

转载 作者:行者123 更新时间:2023-11-28 11:33:52 25 4
gpt4 key购买 nike

我试图记住 Javascript 中称为“发条算术”的东西,我很久以前在有关幻灯片/轮播的教程中读过它。 (术语可能有误,因为我在谷歌中找不到任何有用的东西)

它是以下代码的简写:

a = a + 1;
if (a > total) a = 0;

本质上它是递增的,直到达到总数,当达到总数时,它会重置回 0。这主要用于创建无限滚动的轮播,因为它总是滚动回开头(索引 0) .

有人如何使用上述发条算法将上述 2 行代码写在 1 行中吗?我认为它使用了“余数”运算符 %,但我不记得其他的了。

最佳答案

这称为modular arithmetic ,并且有效地用于时钟:

A familiar use of modular arithmetic is in the 12-hour clock, in which the day is divided into two 12-hour periods. If the time is 7:00 now, then 8 hours later it will be 3:00. Usual addition would suggest that the later time should be 7 + 8 = 15, but this is not the answer because clock time "wraps around" every 12 hours

在 JavaScript 中,您可以执行 modulo operations使用% operator :

The % operator yields the remainder of its operands from an implied division; the left operand is the dividend and the right operand is the divisor.

一些等效的例子:

a = (a+1) % total;
a = ++a % total;
++a, a %= total;

关于JavaScript "clockwork arithmetic",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com