我有例如这些数组:
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/