假设我们有两个这样的文字数组-
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' ]