LoginSignup
0
0

指定の回数だけサイコロを振る

Posted at

inputに振りたい回数分の数値を入れると、全ての出た目とその目が出た回数を表示します。

<input type="number" id="throw-dices" placeholder="投げる回数">
<button id="dice-switch">サイコロを振る</button>
const diceSwitch = document.getElementById('dice-switch')

diceSwitch.addEventListener('click', throwDice)

function throwDice() {
  const numInput = document.getElementById('throw-dices')
  let str = ''
  const array = []
  const resultThrowDice = [
    { 'value': 1, 'count': 0 },
    { 'value': 2, 'count': 0 },
    { 'value': 3, 'count': 0 },
    { 'value': 4, 'count': 0 },
    { 'value': 5, 'count': 0 },
    { 'value': 6, 'count': 0 },
  ]

  for (let i = 0; i < numInput.value; i++) {
    array.push(Math.floor(Math.random() * 6) + 1)
  }

  array.forEach((diceRoll, index) => {
    if (index === 0) {
      str = diceRoll
    } else {
      str += ` , ${diceRoll}`
    }

    resultThrowDice.filter((diceNum) => {
      if(diceNum.value === diceRoll){
        diceNum.count++
      }
    })
  });

  console.log(str);
  console.log(resultThrowDice);
}

// サイコロを1万回振った時の結果
// {value: 1, count: 1689}
// {value: 2, count: 1649}
// {value: 3, count: 1657}
// {value: 4, count: 1671}
// {value: 5, count: 1685}
// {value: 6, count: 1649}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0