Math.random() だけ記述すると、0から1未満の中でランダムに数字が返される。Math.random() で返される値が0.05未満(=5%未満)ならこの処理を行う」といったように条件分岐させていけばよい。<aside> 💫 力技だけど、配列の値で高確率で出したいものだけ意図的に多く書いておく手もあるよ👀
</aside>
例)ボタンクリックで、5%の確率で「大吉」、15%の確率で「中吉」、80%の確率で「凶」を出す(下に動画あり)
"use strict";
{
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
//高確率で出したい値を意図的に多く書いておくパターン【力技】
const results = ["大吉", "大吉", "大吉", "大吉", "凶"];
btn.textContent = results[Math.floor(Math.random() * results.length)];
//Math.random()のみ使用、%と条件分岐で確率操作するパターン
const n = Math.random();
if (n < 0.05) {
//5%の確率で「大吉」を出す
btn.textContent = "大吉";
} else if (n < 0.2) {
//15%の確率で「中吉」を出す(20% - 5% = 15%)
btn.textContent = "中吉";
} else {
//80%の確率で「凶」を出す(20%までは上記で条件を書いたので、残りの80%という意味になる)
btn.textContent = "凶";
}
});
}
▼一応 HTMLとCSSも記載
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>JavaScriptでおみくじ</title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="btn">
おみくじ<br />
スタート
</div>
<script src="./js/index.js"></script>
</body>
</html>
body {
font-family: sans-serif;
background-color: #efefef;
}
#btn {
width: 200px;
height: 200px;
background: #ef454a;
border-radius: 999px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
flex-direction: column;
position: fixed;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
color: #fff;
font-weight: bold;
font-size: 20px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 10px 0 #d1483e;
user-select: none;
text-align: center;
}
#btn span {
display: block;
font-size: 10px;
}
#btn:hover {
opacity: 0.9;
/* box-shadow: 0 5px 0 #d1483e;
top: 51%; */
}
#btn:active {
box-shadow: 0 5px 0 #d1483e;
top: 51%;
}