我正在尝试获得如下所示的结果:Miniors | Boys | 54kg - 62kg
每个值都由竖线 | 分隔来自包含某种“限制类型”的数组。例如:ageGroups, genders, weightClasses
(如上所示)。
我现在能够得到这个结果的方法是,如果我对嵌套的 forEach 循环进行硬编码(使用 underscorejs),但这意味着我现在必须知道我必须循环多少数组才能获得想要的结果。 这工作“很好”:
var categories = [];
_.each(ageGroups, function(ageGroup) {
_.each(gender, function(gender) {
_.each(weightClasses, function(weightClass) {
categories.push(ageGroup.name + ' | ' + gender.name + ' | ' + weightClass.name);
});
});
});
输出是一个数组(类别),其中包含限制数组的所有可能组合。
现在,我的问题是我需要一种方法来对未知数量的限制数组执行相同的操作。 我对一个合适的解决方案的猜测是递归,但是我还没有能够产生任何实际有效的东西,因为我还不能完全理解递归:)
可以在此处找到使用一些测试数据准备的 fiddle : jsFiddle 强>。 fiddle 使用 angular 进行一些简单的数据绑定(bind)和调试结果输出,使用 underscorejs 处理数组。
最佳答案
我最近写了一个递归函数来创建数组的所有组合。您必须将数据转换为我的函数使用的数组数组,但这应该不难。
无论如何,这是带有可运行示例的代码:
var v = [['Miniors','Kadettes','Juniors', 'Seniors'], ['Boys','Girls','Men','Women'],['54kg - 62kg','64kg - 70kg','71kg - 78kg','79kg - 84kg']];
var combos = createCombinations(v);
for(var i = 0; i < combos.length; i++) {
document.getElementsByTagName("body")[0].innerHTML += combos[i] + "<br/>";
}
function createCombinations(fields, currentCombinations) {
//prevent side-effects
var tempFields = fields.slice();
//recursively build a list combinations
var delimiter = ' | ';
if (!tempFields || tempFields.length == 0) {
return currentCombinations;
}
else {
var combinations = [];
var field = tempFields.pop();
for (var valueIndex = 0; valueIndex < field.length; valueIndex++) {
var valueName = field[valueIndex];
if (!currentCombinations || currentCombinations.length == 0) {
var combinationName = valueName;
combinations.push(combinationName);
}
else {
for (var combinationIndex = 0; combinationIndex < currentCombinations.length; combinationIndex++) {
var currentCombination = currentCombinations[combinationIndex];
var combinationName = valueName + delimiter + currentCombination;
combinations.push(combinationName);
}
}
}
return createCombinations(tempFields, combinations);
}
}
关于javascript - 动态嵌套for循环用递归解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26703700/