前端js生成一个随机数
关键函数:
Math.floor()
Math.random()
Math.floor()方法执行向下舍入,既它总是会将数值向下舍入为最接近的整数。
Math.random()方法返回大于等于0小于1的一个随机数。
生成随机数公式:
随机数 = Math.floor(Math.random() * 可能的总数 + 第一个可能的值)
举例
要想生成一个1到10之间(包括1和10)的随机数,可以这样编码
var num = Math.floor(Math.random() * 10 + 1);
总共有10个可能的值(1到10),第一个可能的值是1。
ps: Math对象在js中是单体内置对象,无需引入任何的包即可在js代码中使用。