1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Math.random()を使って確率操作してみる(おみくじ)

Posted at
qiita.js
'use strict';

{
  const btn = document.getElementById('btn');

  btn.addEventListener('click', () => {
    // const results = ['大吉', '中吉', '凶', '大凶'];
    // const results = ['大吉', '中吉', '中吉', '中吉', '凶'];
    // btn.textContent = results[Math.floor(Math.random() * results.length)];
    const n = Math.random();
    if (n < 0.05) {
      btn.textContent = '大吉'; // 確率は5%
    } else if (n < 0.2) {
      btn.textContent = '中吉'; // 確率は15%
    } else {
      btn.textContent = ''; // 確率は80%
    }
  });
}

if (n < 確率)と記述するし、確率操作が可能になる。

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?