Math

在指定范围内,生成随机整数
 
公式:
    Math.floor(Math.random * delta + minNum); // 返回 minNum ~ maxNum (maxNum = minNum + delta -1) 之间的正整数 -- 包含两侧边界值
    关键点是 delta的正确设置
  比如 :
    Math.floor(Math.random() * 10 + 1 ) -- 返回 1~10 之间的整数(包含1和10)
    Math.floor(Math.random() * 9 + 2 )  -- 返回 2~10 之间的整数(包含2和10)
 
利用这个特性,可以提供一个公共函数:
  function genRandom(min,max){
    let delta = Math.abs(max - min + 1);
    return Math.floor(Math.random() * delta + min);
  }
 
以下是验证代码 : set用于去重.
var set = new Set();
for(var i = 0 ; i< 1000 ; i++){
  set.put(Math.floor(Math.random() * 9 + 2 ));
}
console.log(set); // display 2 ~ 10 
 
原文地址:https://www.cnblogs.com/lmxxlm-123/p/11131896.html