从某个范围选择一个值
从某个范围选择一个值,比如1到10,2到9等
可能的个数 = 大数 - 小数 + 1
Math.floor(Math.random()*可能的个数 + 第一个可能的值)
比如 1 到 10,有 10 个数,加第一个可能的数就是加 1
Math.floor(Math.random()*10 + 1)
比如 2 到 10 ,有 9 个数,加第一个最小的数 2
Math.floor(Math.random()*9 + 2)
根据以上抽象出通用的函数
function getRandom(minValue, maxValue) {
const count = maxValue - minValue + 1
return Math.floor(Math.random()*count + minValue)
}
// 应用
getRandom(2,9)
getRandom(20,100)
应用
从数组中随机取出一项
const colors = ['red', 'green', 'blue', 'yellow', 'black', 'purple', 'brown' ]
const color = colors[getRandom(0, colors.length - 1)]
console.log(color)