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

时间:2014-11-02 19:59:08

标签: javascript arrays recursion underscore.js nested-loops

我正在尝试查看类似这样的结果: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);
      });
   });
});

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

现在,我的问题是我需要一种方法来对未知数量的限制数组做同样的事情。 我对正确解决方案的猜测是递归但是我无法生成任何实际可行的内容,因为我还无法绕过递归:)

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

2 个答案:

答案 0 :(得分:3)

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

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

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);
  }
}

答案 1 :(得分:2)

function iterate(lists, fn)
{
  var values = [];
  function process(listIndex)
  {
    var list = lists[listIndex];

    // no list? create the value
    if (!list)
    {
      fn.apply(null, values);
      return;
    }

    for (var i = 0; i < list.length; i++)
    {
      values[listIndex] = list[i];
      process(listIndex+1);
    }
  }

  process(0);
}

这是一个基于您的问题中提到的数据的工作示例:http://jsbin.com/boqucu/2/edit