- 只保留整數(shù)部分(丟棄小數(shù)部分)
parseInt(5.1234); // 5
- 向下取整(<= 該數(shù)值的最大整數(shù),和parseInt()一樣)
Math.floor(5.1234); // 5
- 向上取整(有小數(shù),整數(shù)部分就+1)
Math.ceil(5.1234); // 6
- 四舍五入(小數(shù)部分)
Math.round(5.1234); // 5
Math.round(5.6789); // 6
- 取絕對值
Math.abs(-1); // 1
- 返回兩數(shù)中的較大者
Math.max(1,2); // 2
- 返回兩數(shù)中的較小者
Math.min(1,2); // 1
- 隨機數(shù)(0-1)
Math.random(); //返回 0(包括) 至 1(不包括) 之間的隨機數(shù)
JavaScript 隨機整數(shù)
Math.random() 與 Math.floor() 一起使用用于返回隨機整數(shù)。
Math.floor(Math.random() * 10); // 返回 0 至 9 之間的數(shù)
Math.floor(Math.random() * 11); // 返回 0 至 10 之間的數(shù)
Math.floor(Math.random() * 100); // 返回 0 至 99 之間的數(shù)
Math.floor(Math.random() * 101); // 返回 0 至 100 之間的數(shù)
Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之間的數(shù)
Math.floor(Math.random() * 100) + 1; // 返回 1 至 100 之間的數(shù)
一個適當?shù)碾S機函數(shù)
正如你從上面的例子看到的,創(chuàng)建一個隨機函數(shù)用于生成所有隨機整數(shù)是一個好主意。
這個 JavaScript 函數(shù)始終返回介于 min(包括)和 max(不包括)之間的隨機數(shù):
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
這個 JavaScript 函數(shù)始終返回介于 min 和 max(都包括)之間的隨機數(shù):
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}