我正在做一个纸牌游戏,我需要设置每一手牌的玩家。
我有两个数组,一个存储手牌,另一个存储玩家。
hands = [
{
handNumber: 1,
dealer: null
},
{
handNumber: 2
dealer: null
}
...
]
players = ["Player 1", "Player 2", "Player 3", "Player 4"]
我的目标是以连续的方式为每一手分配一个牌手,直到达到最大手数。例如:
Hand 1: Player 1
Hand 2: Player 2
Hand 3: Player 3
Hand 4: Player 4
Hand 5: Player 1
And so on
我尝试了不同的循环,但我真的被这个卡住了:
hands.forEach(hand => {
for(let i = 0; i < players.length; i++) {
hand.dealer = players[i]
}
})
有什么建议吗?任何帮助都将不胜感激。
发布于 2021-06-04 16:11:39
你可以使用%来返回,永远不会超出播放器数组的范围,并且总是再次返回到开始位置:
例如:0%3 == 0
1%3 == 1
2%3 == 2
3%3 == 0
4%3 == 1
..。
hands.forEach((hand, index) => {
hands[index] = players[index % players.length];
})
如果您感兴趣,可以在此处阅读有关js运算符的更多信息:https://www.w3schools.com/js/js_operators.asp
https://stackoverflow.com/questions/67840514
复制相似问题