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