如何实现两个不同长度数组的元素两两拼接组合?
如何实现两个不等长数组的元素全拼接组合?
这其实就是要生成两个数组的笛卡尔积并完成字符串拼接,属于很常见的数组操作需求,我给你几种不同的实现方式,适配不同的编程习惯:
JavaScript 实现
方式1:嵌套循环(直观易懂,适合新手)
这种方式逻辑最直接,外层遍历第二个数组的每个元素,内层遍历第一个数组的每个元素,逐个拼接后存入结果数组:
const array1 = ["one", "two", "three"]; const array2 = ["twenty", "thirty", "forty", "fifty"]; const arrayWant = []; for (const item2 of array2) { for (const item1 of array1) { arrayWant.push(item2 + item1); } } console.log(arrayWant); // 输出:["twentyone", "twentytwo", "twentythree", "thirtyone", "thirtytwo", "thirtythree", "fortyone", "fortytwo", "fortythree", "fiftyone", "fiftytwo", "fiftythree"]
方式2:函数式写法(简洁优雅)
利用数组的flatMap和map方法,一行代码就能搞定:
const array1 = ["one", "two", "three"]; const array2 = ["twenty", "thirty", "forty", "fifty"]; const arrayWant = array2.flatMap(item2 => array1.map(item1 => item2 + item1)); console.log(arrayWant); // 结果和嵌套循环完全一致
这里flatMap的作用是:先让array2的每个元素通过map生成一组拼接后的子数组,再自动把这些子数组扁平成一个一维数组,完美匹配你的需求。
Python 实现
如果用Python的话,列表推导式是最简洁的写法:
array1 = ["one", "two", "three"] array2 = ["twenty", "thirty", "forty", "fifty"] array_want = [item2 + item1 for item2 in array2 for item1 in array1] print(array_want)
执行后同样会得到你期望的目标数组。
内容的提问来源于stack exchange,提问作者user12151635
相关产品推荐
相关产品推荐

