javascript - 如何从一组数组中获取所有组合

标签 javascript jquery

我有例如这些数组:

a1 = ["1", "2", "3"];
a2 = ["a", "b"];
a3 = ["q", "w", "e"];

result = ["1aq", "1aw", "1ae", "1bq", "1bw", ... "3be"];

如何在没有嵌套循环的情况下获得这个(例如也使用 jquery)? 谢谢

最佳答案

我不明白嵌套循环有什么问题,但这是一个通用的解决方案:

var a = [a1, a2, a3];

var result = [""]; // start with the empty string,
for (var i=0; i<a.length; i++) { // and repeatedly
        var ai = a[i],
            l = ai.length;
    result = $.map(result, function(r) { // make result a new array of
        var ns = []; // new combinations of
        for (var j=0; j<l; j++) // each of the letters in ai
            ns[j] = r + ai[j]; // and the old results
        return ns;
    }); // using the odds of jQuery.map with returned arrays
}
return result;

关于javascript - 如何从一组数组中获取所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14663145/

相关文章:

javascript - MomentJS 检查 isBefore 没有日期

javascript - 创建元素并将事件设置为类时,JQuery 会重复事件

javascript - 我必须在移动浏览器上显示 1000 多个未分类的图片缩略图,我不知道如何

javascript - 无法在自定义指令中调用jquery datetimepicker函数

javascript - 在category.ftl中动态设置值

javascript - jQuery:选择父div之外的下一个div

javascript/Angular : add 'line break' via string

javascript - 如何在不触发更改事件的情况下选中复选框?

javascript - 更改notify js插件自动隐藏延迟时间

javascript - 数字自动收录器计数到值然后停止