我有一系列用于轮播项目的ID
PaymentController
假设我想开始显示id = 2的幻灯片,然后点击下一步按钮显示id = 3。如果它达到id = 4并单击next,则显示id = 1。 (旋转的种类) 单击上一个按钮应该在不同的方向上执行相同的操作。
我想知道在lodash或es6中是否有任何方法可以为我提供此功能,因此我不会在我的应用中为其编写逻辑。
答案 0 :(得分:1)
要进行循环计算,您可以使用原生js remainder (%)运算符:
(currentIndex + 1) % arr.length // currentIndex is the position in the array
const findNextIndex = (currentIndex, arr) => (currentIndex + 1) % arr.length;
const arr = ['A', 'B', 'C', 'D'];
let current = 2; // the start position
const btn = document.getElementById('btn');
const show = document.getElementById('show');
show.innerText = arr[current];
btn.addEventListener('click', function() {
current = findNextIndex(current, arr);
show.innerText = arr[current];
});

<button type="button" id="btn">next</button>
<div id="show"></div>
&#13;