JavaScript 隨機

Math.random()

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

實例

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

親自試一試

Math.random() 總是返回小于 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 函數始終返回介于 minmax(都包括)之間的隨機數:

實例

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

親自試一試