gpt4 book ai didi

javascript - 从 1 到 5 循环数组,如果达到 5,则重新开始 (JavaScript)

转载 作者:行者123 更新时间:2023-11-28 12:22:07 24 4
gpt4 key购买 nike

正如我的问题所说,如何循环遍历包含 1, 2, 3, 4, 5 的数组,当达到 5 时,它再次从 1 开始。

我想向每个元素添加一个名为 g1、g2、g3 的类,如下所示:

<div class="myClass g1"></div>
<div class="myClass g2"></div>

依此类推,第四...当到达g5时,它从g1开始...

问题是,这是迭代并在同一元素中添加 g1 g2 g3 g4 和 g5,我想将它们拆分为每个元素。

到目前为止我的代码:

var addGradient = (function() {
var $serviceModule = $(".service > .service-module > .service-module-bottom");
var $array = [1, 2, 3, 4, 5];

$serviceModule.each(function() {
var $this = $(this);
for (var $i = 1; $i < $array.length; $i++) {
$this.addClass("g" + $array[$i]);
}
});
});

最佳答案

在这里做一个简单的模数学。不需要数组或任何循环,

var addGradient = (function() {
var $serviceModule = $(".service > .service-module > .service-module-bottom");
$serviceModule.each(function(index) {
$this.addClass("g" + ((index % 5)+1));
});
});

关于javascript - 从 1 到 5 循环数组,如果达到 5,则重新开始 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661612/

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