我有一个字符串数组要显示const array = ["one", "two", "three"]; 。
UI 最初显示数组中的第一项,即"one"。从那里我有一个按钮right,单击它会显示下一个项目或字符串,即two,然后three,之后three应该返回one并再次从那里开始。我还有一个left按钮,单击时它显示前一个项目或字符串,如果当前字符串是two,则前一个字符串是one,然后从one开始three并向后走。
我正在使用生成器来做到这一点。这是我的尝试
function* stepGen(steps) {
let index = 0;
while (true) {
const direction = yield steps[index];
index = (index + (direction === "forward" ? 1 : -1)) % steps.length;
}
}
const array = ["one", "two", "three"];
let gen = stepGen(array);
const getNext = () => gen.next("forward").value;
const …Run Code Online (Sandbox Code Playgroud)