You need to enable JavaScript to run this app. 如何实现JS字符串数组各元素内的单词全排列生成算法?
优惠活动
大模型
产品
解决方案
定价
更多

如何实现JS字符串数组各元素内的单词全排列生成算法?

多词数组元素全排列实现

核心处理逻辑

  • 逐一遍历原数组的每个字符串元素
  • 对单个元素按空格拆分出独立的单词列表
  • 为单词列表生成所有不重复的全排列组合
  • 将每个排列的单词重新用空格拼接,汇总为最终输出结果

可直接运行的JavaScript实现代码

// 数组全排列生成工具函数
function getPermutations(arr) {
  const permutations = [];
  // 单元素直接返回,终止递归
  if (arr.length === 1) return [arr];
  for (let index = 0; index < arr.length; index++) {
    const currentWord = arr[index];
    // 取出除当前元素外的剩余元素
    const restWords = [...arr.slice(0, index), ...arr.slice(index + 1)];
    // 递归生成剩余元素的全排列
    const restPerms = getPermutations(restWords);
    // 拼接当前元素与剩余排列,存入结果集
    for (const perm of restPerms) {
      permutations.push([currentWord, ...perm]);
    }
  }
  return permutations;
}

// 主处理函数
function transformArray(originArr) {
  const output = [];
  originArr.forEach(item => {
    // 拆分单词时自动忽略连续的多余空格
    const wordList = item.trim().split(/\s+/);
    // 生成排列并拼接为字符串
    const wordPerms = getPermutations(wordList).map(perm => perm.join(' '));
    output.push(...wordPerms);
  });
  return output;
}

// 测试用例
let myArray = ['big bad wolf','go home'];
const result = transformArray(myArray);
// 逐行打印结果,匹配需求的输出格式
result.forEach(line => console.log(line));

运行输出效果

big bad wolf
big wolf bad
bad big wolf
bad wolf big
wolf big bad
wolf bad big
go home
home go
  • 适配细节:当元素仅包含单个单词时,不会生成重复排列,直接返回原字符串;拆分逻辑兼容元素内存在多段连续空格的异常输入。

内容的提问来源于stack exchange,提问作者Jon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 21:45:03