如何使用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' ]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短