0
0

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.

JavaScriptを使って簡単なおみくじ

Last updated at Posted at 2021-04-08

#仕様
今回はドットインストールより、JavaScript使った簡単なおみくじの作成をしました!

Math.randam()を使い0以上1未満で数値を生成しif文を使い条件別に確立を決め、
ボタンを押すと結果が表示されます。


const btn = document.getElementById("btn");
  btn.addEventListener("click", ()=> {
    const n = Math.random();
    if (n < 0.1) {
      btn.textContent = "大吉";  // 確率を10%に指定
    } else if (n < 0.4) {
      btn.textContent = "中吉";  // 確立を30%指定
    } else {
      btn.textContent = "";  // 確立を50%指定

  • 0以上1未満の数値がランダムでnに代入される

  • nが0.1未満なら”大吉”

  • nが0.1以上0.4未満なら”中吉”

  • nが0.4以上1未満なら”凶”

##メモ
その他パターンでも参照します。

const results = ["大吉", "", "中吉","小吉", "末吉", ""];
     const n = Math.floor(Math.random() * results.length);
     btn.textContent = results[n];

  • lengthプロパティ で results=[ ]配列の要素数を表現

const results = ["大吉", "", "中吉","小吉", "末吉", ""];
     btn.textContent = results[Math.floor(Math.random() * results.length)];

  • results[n] に 二列目を直接代入
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?