如何在 JavaScript 中为两个数组的内容创建所有可能的组合
假设我们有两个这样的字面量数组:
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' ]
广告