vue2 多个数组如何按照要求合并成一个数组?

作者站长头像
站长
· 阅读数 12

我正在开发一个商城在开发【发布商品】的模块时,遇到了一个问题,希望高手解答

现在有多个数组:

a = [1,2,3,4,5]
b = [a,b,c]
c = [A,Z]

请问如何才能重组成类似于下面的数组

mix = ['1aA','1aZ','1bA','1bZ','1cA','1cZ','2aA','2aZ'..........]

请问大佬如何实现呢?另外,这种功能叫什么?

回复
1个回答
avatar
test
2024-07-12

固定数组解法:answer image

  const a = [1, 2, 3, 4, 5];
  const b = ['a', 'b', 'c'];
  const c = ['A', 'Z'];
  const result = [];
  for (let aItem of a) {
    for (let bItem of b) {
      for (let cItem of c) {
        result.push('' + aItem + bItem + cItem);
      }
    }
  }
  console.log(result);

任意数组解法:answer image

const demo=function(...args) {
  const result = [];
  const arrays = args.filter(arg => arg.length);
  build(arrays, 0, '', result);
  console.log(result);
};
const build=function (arrays, index, str, result) {
  const array = arrays[index++];
  if (!array) {
    result.push(str);
    return;
  }
  for (let item of array) {
    build(arrays, index, str + item, result);
  }
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容