如何使用JavaScript动态组合所有提供的数组?
假设我们有两个像这样的文字数组-
const arr1= ['a', 'b', 'c']; const arr2= ['d', 'e', 'f'];
我们需要编写一个JavaScript函数,该函数接受两个这样的数组,并从该数组构建所有可能的组合。
因此,对于这两个数组,输出应类似于-
const output = [ad, ae, af, bd, be, bf, cd, ce, cf];
示例
为此的代码将是-
const arr1= ['a', 'b', 'c'];
const arr2= ['d', 'e', 'f'];
const combineArrays = (...arr) => {
const res = [];
const combinePart = (part, index) => {
arr[index].forEach(el => {
const p = part.concat(el);
if(p.length === arr.length){
res.push(p.join(''));
return;
};
combinePart(p, index + 1);
});
};
combinePart([], 0);
return res;
}
console.log(combineArrays(arr1, arr2));输出结果
控制台中的输出将是-
[ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]