我试图得到如下所示的结果: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);
});
});
});
输出是一个数组(类别),其中包含限制数组的所有可能组合。
现在,我的问题是我需要一种方法来对未知数量的限制数组执行相同的操作。
我对正确解决方案的猜测是递归, BUT我还没有能够产生任何实际有效的东西,因为我还不能理解递归:)
可以在这里找到用一些测试数据准备的小提琴:jsFiddle。
小提琴使用 Angular 进行一些简单的数据绑定和调试结果输出,并使用 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)