如何在 JavaScript 中为两个数组的内容创建所有可能的组合
javascriptweb developmentfront end technologyobject oriented programming
假设我们有两个像这样的文字数组 −
const arr1 = ["A","B","C"]; const arr2 = ["1","2","3"];
我们需要编写一个 JavaScript 函数,该函数接受两个这样的文字数组。然后,该函数应将第一个数组的每个元素与第二个数组的每个元素组合起来,并将它们推送到一个新数组中。
因此,上述输入的输出应如下所示 −
const output = ["A1","A2","A3","B1","B2","B3","C1","C2","C3"];
示例
其代码为 −
const arr1 = ["A","B","C"]; const arr2 = ["1","2","3"]; const prepareCartesian = (arr1 = [], arr2 = []) => { const res = []; for(let i = 0; i < arr1.length; i++){ for(let j = 0; j < arr2.length; j++){ res.push(arr1[i] + arr2[j]) } }; return res; }; console.log(prepareCartesian(arr1, arr2));
输出
控制台中的输出将是 −
[ 'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3' ]