如何使用 JavaScript 动态组合所有提供的数组?
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 18:20:17
假设我们有两个像这样的文字数组 −
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' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

