【问题标题】:Generate all possible combinations of strings from two arrays (javascript)从两个数组生成所有可能的字符串组合(javascript)
【发布时间】:2021-01-14 03:36:23
【问题描述】:

我目前有两个如下所示的数组:

let suits = ['♣', '♦', '♥', '♠'];
let cards = ['A','2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];

我想将这些组合起来以包含一个由 52 个字符串组成的数组,其中包含所有可能的卡片组合。例如:

['A♣', 'A♦', 'A♥', 'A♠', '2♣' ...]

我知道我可以编写两个嵌套的“for 循环”并将它们连接起来,但是有没有更有效的方法来做到这一点?

谢谢!

【问题讨论】:

标签: javascript string combinations


【解决方案1】:

您可以使用Array.prototype.flatMap() 方法。

const suits = ['♣', '♦', '♥', '♠'];
const cards = ['A','2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const ret = cards.flatMap((x) => suits.map((y) => `${x}${y}`));
console.log(ret);

【讨论】:

    【解决方案2】:

    你可以这样做:

    const suits = ['♣','♦','♥','♠']
      ,   cards = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
      ;
    const deck = cards.reduce((d,c)=>[...d,...suits.map(s=>s+c)],[])
    
    console.log( deck )
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    或者:

    const deck = Array.from({length:52},(_,i)=>suits[Math.floor(i/13)]+cards[i%13])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多