1. 程式人生 > 實用技巧 >Js隨機Math.random()

Js隨機Math.random()

Math.random()返回 0(包括) 至 1(不包括) 之間的隨機數:

例項

Math.random();                // 返回隨機數

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 之間的數

廣州品牌設計公司https://www.houdianzi.com PPT模板下載大全https://redbox.wode007.com

一個適當的隨機函式

正如你從上面的例子看到的,建立一個隨機函式用於生成所有隨機整數是一個好主意。這個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;
}