JS 随机数

前言:
对象在JavaScript 中被称为引用类型的值。

Math 是引用类型的单体内置对象,Math对象提供了很多属性和方法,用于辅助完成复杂的数学计算任务。

Math 对象方法

方法 描述
Math.ceil(x) 进行上舍入,即向上取整。 例:Math.ceil(25.9) //26 Math.ceil(25.1) //26
Math.floor(x) 进行向下舍入,即向下取整。 例:Math.floor(25.9) //25 Math.floor(25.1) //25
Math.round(x) 进行四舍五入(标准舍入)。 例:Math.floor(25.5) //26 Math.floor(25.1) //25
Math.random() 返回 0 ~ 1 之间的随机数,包含 0 不包含 1

random 方法

值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)

举例: 生成 (1 ~ 10 之间的数值)

let num = Math.floor(Math.random() * 10 + 1);

生成[n,m]的随机整数

函数功能:生成[n,m]的随机整数。

// 包括 min ~ max 的数值
 function selectFrom(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
 }
 console.log(selectFrom(2,6));  //包括 2 ~ 6 的数值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章