<script> var rand = {}; rand.getInt = function (begin,end){ return Math.floor(Math.random()*(end-begin + 1)) + begin; } var v = rand.getInt(0,3) alert(v); </script>
常见错误写法:
<script> var rand = {}; rand.getInt = function (begin,end){ return Math.floor(Math.random()*(end-begin)) + begin; } var v = rand.getInt(0,3) alert(v); </script>
因为javascirpt的Math.random()的范围是[0,1),包含0,不包含1,错误写法中,因为Math.floor是向下取整,所以:
Math.floor([0,1) * 3) + 0 的取值范围是[0,1,2],永远取不到3.
<script> var rand = {}; rand.get = function (begin,end,precision){ return (Math.random()*(end-begin) + begin).toFixed(precision); } var v = rand.get(0,3,2) alert(v); </script>
这样取不到3,也是个问题,没有什么好办法吗?