天天看點

生成一個指定範圍内的随機數

使用

Math.random()

生成随機值,使用乘法将其映射到所需的範圍。

const random = (min, max) => Math.floor(Math.random() * (max - min)) + min
           

為了友善了解,我們将該方法拆解一下:

const MIN = 1
const MAX = 4

// 用減法算出內插補點
const DELTA = MAX - MIN

const initialRandom = Math.random()

// 将随機數乘以內插補點
const multiplied = initialRandom * DELTA

// 使用 Math.floor 将其四舍五入
const floored = Math.floor(multiplied)

// 加上最小值,我們将其向上移動以完美比對範圍:
const answer = floored + MIN
           

此随機方法包括下限,但不包括上限。例如,

random(10, 12)

将随機 10 或 11,但從不随機 12。

這是有意做的,以比對

Math.random

以及

slice

等 JavaScript 方法的行為。

// 從 [10, 11, 12, 13] 中擷取一個随機數
console.log(random(10, 14))

// 擷取從 1 到 100(包含 100)的随機數
console.log(random(1, 101))

// 擷取一個從 -10 到 10(包含 10)的随機數
console.log(random(-10, 11))
           

繼續閱讀