我有以下Javascript,旨在使用户能够使用由array
执行的eventListener
函数来循环往返许多菜单......
var i = 0;
var steps = [
function one() {do something},
function two() {do something},
function three() {do something},
function four() {do something},
function five() {do something}
]
//loops forward through array *successfully*
document.getElementById('forward').addEventListener("click", function() {
steps[i]();
}
//loops backwards through array *unsuccessfully*
document.getElementById('backward').addEventListener("click", function() {
steps[i]().reverse();
}
第一个eventListener
函数成功循环通过array
,然而,第二个eventListener
函数向后,无法反向循环遍历数组(令人惊讶)。
首先,我不确定如何循环一个包含函数的array
。
其次,我想知道是否有可能从array
的特定点反向循环array
;基本上,如果array
已经循环,并且没有比函数three()更进一步,是否有一个脚本允许用户向后循环到函数two()然后一个(),然后再转发?
我已经在StackOverflow上阅读了一些关于array.reverse()的问题,但是我发现没有一个问题似乎涉及函数的存在和/或反转循环中间数组。
非常感谢您的回答,非常感谢!
我认为你不需要遍历数组。你需要“管理状态”,这意味着你增加和减少i
。更新状态后,使用steps[i]
找到正确的函数并调用它。
var activeMenuIndex = 0;
var steps = [
function one() {console.log("activate menu 1") },
function two() {console.log("activate menu 2") },
function three() {console.log("activate menu 3") },
function four() {console.log("activate menu 4") },
function five() {console.log("activate menu 5") }
];
var activateCurrentMenu = function() {
var activator = steps[activeMenuIndex];
if (activator) {
activator();
} else {
console.log("Out of bounds!");
}
};
var nextMenu = function() {
// TODO: Check for out of bounds
activeMenuIndex += 1;
activateCurrentMenu();
};
var prevMenu = function() {
// TODO: Check for out of bounds
activeMenuIndex -= 1;
activateCurrentMenu();
};
document.getElementById('forward').addEventListener("click", nextMenu);
document.getElementById('backward').addEventListener("click", prevMenu);
<button id="backward">back</button>
<button id="forward">next</button>
回答这个问题:循环遍历一个函数数组与循环任何其他数组没有什么不同。您可以使用for
块,或使用foreach
。
如果要反向循环数组,可以调用.reverse().foreach
(它会改变原始数组)。
这是你在找什么?循环遍历数组
var steps = [
function one() { console.log("1") },
function two() { console.log("2") },
function three(){ console.log("3") },
function four() { console.log("4") },
function five() { console.log("5") }
]
//loops forward through array
function forward(i){
steps.slice(0,i).forEach(function(el){ el(); });
}
//loops backwards through a the reversed aarray
function backward(i) {
steps.reverse().slice(0,i).forEach(function(el){ el(); });
}
forward(3);
backward(3);