今天在折腾广告位随机显示不同图片及链接的时候(详见『如何通过 JS 实现广告位随机显示不同图片及链接?』)发现代码中有 Math.floor()和 Math.random(),但是不知道是什么意思,幸好万能的网络可以让我们学习。
Math.floor()
Math.floor(X):返回小于或等于一个给定数字的最大整数,是向下取整。X 是一个数字。
例如:
- Math.floor(11.2); 返回 11
- Math.floor(11.99);返回 11
- Math.floor(0.5 ); 返回 0
- Math.floor(-11.2); 返回-12
- Math.floor(-11.99); 返回-12
想了解更多内容请移步MDN>>Math.floor()
Math.random()
Math.random():一个浮点型伪随机数字,在 0(包括 0)和 1(不包括)之间,如 0.0507989722044071。
- [0,1) === [即从 0(包含 0)到…1 但不包括 1(排除 1)。
- [0,1) === 左闭右开区间
想了解更多内容请移步MDN>>Math.random()