gpt4 book ai didi

javascript - 尝试使用 For Loop 创建一副纸牌

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:36 25 4
gpt4 key购买 nike

我正在尝试使用 2 个数组创建一副纸牌。一个数组是花色,另一个是值。我的想法是使用 for 循环遍历数组来创建 52 张卡片组。但是,我似乎无法正确使用语法。

我尝试使用 forEach 方法。

var deck = [];
var suits = ["diamonds", "spades", "hearts", "clubs"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

suits.forEach(function(suits) {
deck.push(suits);
deck.push(values);
});

console.log(deck)

最佳答案

您需要两个循环,一个在花色上,一个在面值上,例如

var deck = [];
var suits = ["diamonds", "spades", "hearts", "clubs"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

suits.forEach(function(suit) {
values.forEach(function(value) {
deck.push(`${value} of ${suit}`);
});
});

console.log(deck);

或者,您可以使用 flatMap :

var suits = ["diamonds", "spades", "hearts", "clubs"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var deck = suits.flatMap(suit => values.map(value => `${value} of ${suit}`));

console.log(deck);

注意:某些旧版浏览器不支持 flatMap,因此您可能需要 polyfill。

并且仅出于演示目的,您也可以使用 Ramda 执行此操作的 mapxprod :

var suits = ["diamonds", "spades", "hearts", "clubs"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var deck = R.map(([suit, value]) => `${value} of ${suit}`, R.xprod(suits, values));

console.log(deck);
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

关于javascript - 尝试使用 For Loop 创建一副纸牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56116717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com