动态嵌套for循环,用递归解决

aup*_*aup 5 javascript arrays recursion nested-loops underscore.js

我试图得到一个像这样的结果: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);
      });
   });
});
Run Code Online (Sandbox Code Playgroud)

输出是一个数组(类别),包含限制数组的所有可能组合.

现在,我的问题是我需要一种方法来对未知数量的限制数组做同样的事情.我对一个正确的解决方案的猜测是递归,我还没有能够产生任何实际工作的东西,因为我还没有能够绕着递归包裹:)

可以在这里找到一些用一些测试数据准备的小提琴:jsFiddle.小提琴使用angular来进行一些简单的数据绑定和调试结果输出和下划线来处理数组.

dav*_*ave 5

我最近编写了一个递归函数来创建数组的所有组合。您必须将数据转换为我的函数使用的数组数组,但这应该不难。

无论如何,这是带有可运行示例的代码:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)