代码之家  ›  专栏  ›  技术社区  ›  dan richardson

jquery/javascript多数组组合

  •  4
  • dan richardson  · 技术社区  · 15 年前

    我一直在试图找到解决这个问题的办法,但没有用。我要实现的目标是找到多个列表的所有唯一组合。所以,假设我有3个复选框列表(但这是现实应用程序中未知的数字)、颜色、大小、包装大小。列表中的项目将是unqiue。

    [0] => ['blue', 'green']
    [1] => ['small', 'medium', 'large']
    [2] => ['Pack Of 6', 'Pack Of 8']
    

    我想得到” 蓝色,小,6件装 “,” 蓝色,中号,6件装 “,” 蓝色,大号,6件装 “,” 蓝色,小,8件装 “,” 蓝色,中号,8件装 “等等。 排序并不重要,但最好按逻辑分组。

    我已经使用jquery将列表提取到一个数组中:

           options = [];
    
           jQuery('.option-types').each(function(){
                opts = [];
                jQuery('input:checked', this).each(function(){
                    opts.push(jQuery(this).next().text());
                });
                options.push(opts)
            });
    

    如果有一个递归的函数路径来回答这个问题,这将是理想的,正如我所说,列表的数量可以是任何东西,也可以是列表的内容。

    希望你们能帮忙,这是我的头。

    欢呼-丹

    2 回复  |  直到 15 年前
        1
  •  6
  •   jantimon    15 年前

    这应该有效:)

    var recursiveSearch;
    var possibilities = [];
    
    recursiveSearch = function (text, depth )
    {
     text = text || "";
     depth = depth || 0;
     for ( var i = 0; i < options[depth].length; i++ )
     {
       // is there one more layer?
       if ( depth +1 < options.length )
         // yes: iterate the layer
         recursiveSearch ( text + ((text=="") ? "" : " ") + options[depth][i] , depth +1 );
       else
         // no: this is the last layer. we add the result to the array
         possibilities.push ( text + options[depth][i] );
     }
    }
    
    
    recursiveSearch ( );
    

    用你的数组

    [0] => ['blue', 'green']
    [1] => ['small', 'medium', 'large']
    [2] => ['Pack Of 6', 'Pack Of 8']
    

    结果是这样的:

    1. 蓝色小包6个
    2. 蓝色小包8个
    3. 蓝色中等包装6件
        2
  •  0
  •   simon    15 年前

    您可以从页面中修改Java源代码 http://www.1your.com/drupal/FullCodeFindingAllStringCombinationsUsingRecursion 对于JavaScript——即使你对Java没有太多的了解,这个想法也应该是容易理解的。我怀疑是否有现成的解决办法。