如何用JavaScript实现4个字段的元素全组合功能(附示例)
JavaScript实现多字段元素全组合功能
我们需要实现一个功能:把多个字段的元素做全组合,每个字段取一个元素拼接成字符串,最终所有组合用*分隔开。
示例输入:
- Field1:
[1,2] - Field2:
[3,4] - Field3:
[5,6] - Field4:
[7,8]
期望输出:1357 * 1358 * 1367 * 1368 * 1457 * 1458 * 1467 * 1468 * 2357 * 2358 * 2367 * 2368 * 2457 * 2458 * 2467 * 2468
实现代码
下面的函数支持任意数量的字段组合,不止局限于4个:
function generateAllCombinations(fields) { // 初始组合为空字符串的数组 let combinations = ['']; // 遍历每个字段 for (const field of fields) { const tempCombos = []; // 把现有组合和当前字段的每个元素逐一拼接 for (const existingCombo of combinations) { for (const item of field) { tempCombos.push(existingCombo + item); } } // 更新组合列表为新生成的组合 combinations = tempCombos; } // 用*分隔所有组合并返回 return combinations.join(' * '); } // 测试示例 const inputFields = [ [1, 2], [3, 4], [5, 6], [7, 8] ]; const finalResult = generateAllCombinations(inputFields); console.log(finalResult); // 输出结果和期望一致
额外说明
如果后续需要增加字段(比如新增Field5: [9,10]),只需要把对应的数组加入inputFields参数里,函数会自动生成包含新字段的所有全组合,不用修改核心逻辑。
内容的提问来源于stack exchange,提问作者Rain Developer
相关产品推荐
相关产品推荐

