You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:30:47