【JavaScript】简单取随机数 ~~(Math.random() * number)

~~(Math.random() * number)

~~ 取反后再取反,正数向下取整,负数向上取整,

例如 1.2 和 1.8 经运算返回 2

-1.2 和 -1.8 经运算返回 -1

Math.random() * number

返回一个位于开区间 (0, number) 的数字,

向下取整后得到位于闭区间 [0, number - 1] ∈ Z 的数字。

封装一个取随机数的函数

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

猜你喜欢

转载自blog.csdn.net/qq_16181837/article/details/106300966