在 JavaScript 中使用 mod 运算符环绕

Using mod operator in JavaScript to wrap around

我正在使用 ReactJS 构建德州扑克 Web 应用程序。为了跟踪经销商按钮,我使用以下公式...

let currentPlayers = [
    {name: "Foo", position: 1}, 
    {name: "Bar", position: 2},
    {name: "Baz", position: 3} 
]
let dealerButtonPos = 1

dealerButtonPos = ((dealerButtonPos + currentPlayers.length ) % currentPlayers.length + 1 )

我在这里要做的是确保庄家按钮从位置 1 开始,并且在每一轮开始时始终位于正确的位置。在这种情况下,庄家按钮应该总是落在位置 1,然后是 2,然后是 3,然后又是 1。

每轮结束时都会调用带有公式的函数。这应该为最多 8 个玩家正确旋转经销商按钮。 我会一直处于正确的玩家位置吗?我是否正确实施了这一点?我很难概念化并达到这一点。有人可以清楚地解释 mod 运算符吗?

iterator pattern

let currentPlayers = [
    {name: "Foo", position: 1}, 
    {name: "Bar", position: 2},
    {name: "Baz", position: 3} 
]

function* currentPlayersIterator(players) {
  let index = 0;
  while(true)
    if (index < players.length) {
      yield players[index++]
    } else {
      index = 0
      yield players[index++]
    }
}


let i = currentPlayersIterator(currentPlayers)

console.log(i.next().value)
console.log(i.next().value)
console.log(i.next().value)
console.log(i.next().value)
console.log(i.next().value)

我会这样做。

let currentPlayers = [
    {name: "Foo", position: 1}, 
    {name: "Bar", position: 2},
    {name: "Baz", position: 3} 
]
let dealerButtonPos = 1
var index = dealerButtonPos % currentPlayers.length
dealerButtonPos = (index == 0) ? index + currentPlayers.length : index