js随机数
Math.ceil(Math.random()*10); // 获取从 1 到 10 的随机整数,取 0 的概率极小。
Math.round(Math.random()); // 可均衡获取 0 到 1 的随机整数。
Math.floor(Math.random()*10); // 可均衡获取 0 到 9 的随机整数。
Math.round(Math.random()*10); // 基本均衡获取 0 到 10 的随机整数,其中获取最小值 0 和最大值 10 的几率少一半。
Math.random() 生成 [0,1) 的数,所以 Math.random()*5 生成 {0,5) 的数。
通常期望得到整数,所以要对得到的结果处理一下。
parseInt(),Math.floor(),Math.ceil() 和 Math.round() 都可得到整数。
parseInt() 和 Math.floor() 结果都是向下取整。
所以 Math.random()*5 生成的都是 [0,4] 的随机整数。
所以生成 [1,max] 的随机数,公式如下:
// max - 期望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);
所以生成 [0,max] 到任意数的随机数,公式如下:
// max - 期望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));
所以希望生成 [min,max] 的随机数,公式如下:
// max - 期望的最大值
// min - 期望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);
原文链接:http://www.cnblogs.com/starof/p/4988516.html
本文作者: 永生
本文链接: https://yys.zone/detail/?id=185
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
评论列表 (0 条评论)