Math.random() 回傳 0(包括) 至 1(不包括) 之間的亂數:
實體
1 Math.random(); // 回傳亂數
JavaScript 隨機整數
Math.random() 與 Math.floor() 一起使用用于回傳隨機整數,
實體
1 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; }
文章來源:www.sysoft.net.cn,加v:15844800162深度交流
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/167015.html
標籤:JavaScript
上一篇:ES6 Promise
