I am trying to make a realistic unbiased JavaScript dice using Math random object. I want a number from 2-12 to appear on the webpage when I click but it doesn’t return. What is wrong with my code.
<html>
<head><title>DiceBoy</title>
</head>
<body>
<script>
function getRandom(){
var num=Math.random();
if(num < 0.0278) return 2;
else if(num < 0.0834) return 3;
else if(num < 0.1667) return 4;
else if(num < 0.2778) return 5;
else if(num < 0.4167) return 6;
else if(num < 0.5834) return 7;
else if(num < 0.7223) return 8;
else if(num < 0.8334) return 9;
else if(num < 0.9167) return 10;
else if(num < 0.9723) return 11;
else return 12;
var x=getRandom();
document.write(x);
}
</script>
<input type="button" value="Click Here" onClick="getRandom();">
</body>
</html>
Your return statments will exit the method when they are reached, and the rest of the code is not run. You also do not want to call your getRandom method from within the method, or you will have a never ending loop. Rather then returning the number (since no one is listening to the return value) store it in a variable and then use it in the last two lines.