专否 写文章

jerkzhang

Dec 12, 2018
Follow

JavaScript Random随机数专题

万变不离其宗,实现各种功能靠的都是Math.random()方法

  • Math.random() - 返回[0,1)区间的随机数
  • Math.floor() + Math.random() - 获取[0,9]区间的随机整数
  • 自定义函数 - 获取 [ min, max ) 区间的随机整数
  • 自定义函数 - 获取 [ min, max ] 区间的随机整数

Math.random() - 返回[0,1)区间的随机数

Math.random()可返回[0,1)区间的随机数。(所谓的0到1,包括0,但1不包括在内;换言之,假设随机出现的实数为x,那么 0 <= x < 1 )

Math.random();     // 返回[0,1)区间的随机数

运行一下

Math.floor() + Math.random() - 获取[0,9]区间的随机整数

Math.floor()方法是去尾取整函数,搭配Math.random()方法,如下即可获取[0,9]区间的随机整数

Math.floor(Math.random() * 10);     // 返回0-9之间的随机整数
Math.floor(Math.random() * 11);     // 返回0-10之间的随机整数
Math.floor(Math.random() * 12);     // 返回0-11之间的随机整数
...
Math.floor(Math.random() * 10) + 1;     // 返回1-10之间的随机整数

运行一下

自定义函数 - 获取指定区间中的随机整数

函数1:获取 [ min, max ) 区间的随机整数(max不包括在内)

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min) ) + min;
}

运行一下

函数2:获取 [ min, max ] 区间的随机整数(max包括在内)

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}

运行一下

喜欢这个文章 | 分享 | 新建跟帖