可变数量的嵌套for循环 [英] Variable amount of nested for loops
问题描述
编辑:对不起,但我忘了提到我需要计数器变量的值。所以制作一个循环不是我害怕的解决方案。
我不确定这是否可行,但我想请执行下列操作。
对于函数,传递一个数字数组。每个数字都是for循环的上限,例如,如果数组是 [2,3,5]
,则应执行以下代码:
I'm not sure if this is possible at all, but I would like to do the following.
To a function, an array of numbers is passed. Each number is the upper limit of a for loop, for example, if the array is [2, 3, 5]
, the following code should be executed:
for(var a = 0; a < 2; a++) {
for(var b = 0; b < 3; b++) {
for(var c = 0; c < 5; c++) {
doSomething([a, b, c]);
}
}
}
所以嵌套的数量是多少循环等于数组的长度。有没有办法让这项工作?我正在考虑创建一段代码,将每个for循环添加到一个字符串,然后通过 eval
进行评估。不过我读过 eval
不应该是首选,因为它也会产生危险的结果。
So the amount of nested for loops is equal to the length of the array. Would there be any way to make this work? I was thinking of creating a piece of code which adds each for loop to a string, and then evaluates it through eval
. I've read however that eval
should not be one's first choice as it can have dangerous results too.
什么技术可能适合这里?
What technique might be appropriate here?
推荐答案
递归可以很好地解决这个问题:
Recursion can solve this problem neatly:
function callManyTimes(maxIndices, func) {
doCallManyTimes(maxIndices, func, [], 0);
}
function doCallManyTimes(maxIndices, func, args, index) {
if (maxIndices.length == 0) {
func(args);
} else {
var rest = maxIndices.slice(1);
for (args[index] = 0; args[index] < maxIndices[0]; ++args[index]) {
doCallManyTimes(rest, func, args, index + 1);
}
}
}
这样称呼:
callManyTimes([2,3,5], doSomething);
这篇关于可变数量的嵌套for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!