JavaScript - Zufallszahlen
Quelle: https://wiki.selfhtml.org/wiki/JavaScript/Anwendung_und_Praxis/Zufallszahlen (2017-03)
<sytaxhighlight lang="javascript"> var min = 5; var max = 10; var x = Math.floor(Math.random() * (max - min + 1)) + min; </syntaxhighlight>
Beispiel <sytaxhighlight lang="javascript"> var test = { results : { mathfloor : [], mathround : [] }, min : 5, max : 10, iterations : 120000, drawings : 0, randFloor : function () { return Math.floor(Math.random() * (test.max - test.min + 1)) + test.min; }, randRound : function () { return Math.round(Math.random() * (test.max - test.min)) + test.min; }, start : function (button) { for (var i = 0; i < test.iterations; i++) { test.save("mathfloor", test.randFloor()); test.save("mathround", test.randRound()); } test.drawings += test.iterations; test.report(); }, save : function (type, n) { var resultArray = test.results[type]; if (typeof resultArray[n] == "number") { resultArray[n]++; } else { resultArray[n] = 1; } }, report : function () { var tbody = document.getElementById("ausgabe"); var child = tbody.firstChild; for (var i = tbody.childNodes.length - 1, child; i >= 0; i--) { tbody.removeChild(tbody.childNodes[i]); } var html = ""; for (var i = test.min; i <= test.max; i++) { var nRound = test.results.mathround[i]; var pRound = (nRound / test.drawings).toString().substr(0, 6); var nFloor = test.results.mathfloor[i]; var pFloor = (nFloor / test.drawings).toString().substr(0, 6); var row = tbody.insertRow(-1); (row.insertCell(-1)).appendChild(document.createTextNode(i)); (row.insertCell(-1)).appendChild(document.createTextNode(nRound)); (row.insertCell(-1)).appendChild(document.createTextNode(pRound)); (row.insertCell(-1)).appendChild(document.createTextNode(nFloor)); (row.insertCell(-1)).appendChild(document.createTextNode(pFloor)); } }
};
</syntaxhighlight>